@PropertySource 可以加载指定的属性文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和
@ConfigurationProperties 使用。
使用方法
@Data
public class TestProperty {
private String name;
private Boolean male;
private Integer age;
private List<String> alias;
private Map<String, Integer> score;
}
@Configuration
@PropertySource({"classpath:/config/box.properties"})
public class BoxPropertyConfig {
@Bean
@ConfigurationProperties("box")
@ConditionalOnProperty(prefix = "box.test", name = {"enabled"})
@ConditionalOnMissingBean
public TestProperty testProperty() {
return new TestProperty();
}
}
// src/main/resource/config/box.properties
box.name=yuan
box.male=true
box.age=20
box.alias=a,b,c
box.score.Chinese=80
box.score.math=100
box.score.English=90
// src/main/resource/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.box.basic.config.BoxPropertyConfig
- 可以实现 TestProperty Bean的属性注入。
- 同时可以在 application.yml 或者 application-dev.yml 定义同名属性进行 值的覆盖。
- 通过注解@PropertySource导入进来的属性源的优先级是最低的。
动态更新
若系统接入Apollo,使用Apollo进行动态更新属性值,不生效,原因在于 @ConfigurationProperties 目前不支持属性值的热更新。
法一:
可以考虑使用 @Value 进行属性注入,能够实现 动态更新属性值。
法二:
创建 ApolloConfigChangeListener ,发布环境变量变更Event。
@Component
public class ApolloConfig implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ApolloConfigChangeListener
private void someOnChange(ConfigChangeEvent changeEvent) {
Set<String> changedKeys = changeEvent.changedKeys();
changedKeys.forEach(k -> {
ConfigChange change = changeEvent.getChange(k);
log.info(change.toString());
});
// 更新@ConfigurationProperties注解的bean
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
}
}
参考
- https://blog.csdn.net/lkg5211314/article/details/123938380
- https://blog.csdn.net/TomCosin/article/details/123821092
- https://developer.aliyun.com/article/911386