动态配置简单说明
替代本地项目application.properties或者application.yml
- 定义开关
/**
*
* @author hejian
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TestPropertyPlaceholderConfigurer.class)
public @interface EnableDisConfig {
}

2.PropertySourcesPlaceholderConfigurer
提供配置解析功能,模拟远程拉取配置
/**
*
* @author hejian
*
*/
public class TestPropertyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer implements Ordered {
@Override
protected void loadProperties(Properties props) throws IOException {
// 远程配置中心拉取当前应用的所有配置项,构建成Properties对象,委托spring进行解析占位符${""}
props.put("name", "test");
System.out.println("in success");
super.setLocalOverride(true);
super.loadProperties(props);
}
@Override
public int getOrder() {
return -1;
}
}
- 热更新
动态通知应用变更k-v,获取spring容器对象,处理@value注解,重新赋值
/**
* 动态通知应用变更k-v,获取spring容器对象,处理@value注解,重新赋值
*/
String[] beans = applicationContext.getBeanDefinitionNames();
Assert.noNullElements(beans,"无实例化bean对象");
for (String beanName : beans) {
Class<?> bean = applicationContext.getType(beanName);
ReflectionUtils.doWithFields(bean, new FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
System.out.println("BeanName:" + beanName);
System.out.println("Bean的类型:" + bean);
System.out.println("Bean所在的包:" + bean.getPackage());
System.out.println(">>>>>>>" + field.getName());
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, applicationContext.getBean(beanName), value);
}
}, new FieldFilter() {
@Override
public boolean matches(Field field) {
return field.isAnnotationPresent(Value.class) && key.equals(StringResolver.getValue(field.getAnnotation(Value.class).value()));
}
});
}
}
- 测试结果
OK
/**
*
* @author hejian
*
*/
@Component
public class TestManage {
@Autowired
private Environment env;
@Value("${name}")
private String name;
@PostConstruct
public String getName() {
System.out.println(env.getProperty("test.msg"));
System.out.println(env.getProperty("server.port"));
return name;
}
}



网友评论