動態(tài)配置簡單說明
替代本地項目application.properties或者application.yml
- 定義開關(guān)
/**
*
* @author hejian
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TestPropertyPlaceholderConfigurer.class)
public @interface EnableDisConfig {
}
image.png
2.PropertySourcesPlaceholderConfigurer
提供配置解析功能,模擬遠(yuǎn)程拉取配置
/**
*
* @author hejian
*
*/
public class TestPropertyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer implements Ordered {
@Override
protected void loadProperties(Properties props) throws IOException {
// 遠(yuǎn)程配置中心拉取當(dāng)前應(yīng)用的所有配置項,構(gòu)建成Properties對象痪伦,委托spring進(jìn)行解析占位符${""}
props.put("name", "test");
System.out.println("in success");
super.setLocalOverride(true);
super.loadProperties(props);
}
@Override
public int getOrder() {
return -1;
}
}
- 熱更新
動態(tài)通知應(yīng)用變更k-v,獲取spring容器對象饵骨,處理@value注解,重新賦值
/**
* 動態(tài)通知應(yīng)用變更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()));
}
});
}
}
- 測試結(jié)果
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;
}
}
image.png
image.png
image.png