@PropertySource 使用

阅读: 评论:0

@PropertySource 使用

@PropertySource 使用

@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 = &#st", name = {"enabled"})@ConditionalOnMissingBeanpublic TestProperty testProperty() {return new TestProperty();}
}// src/main/resource/config/box.properties
box.name=yuan
box.male=true
box.age=20
box.alias=a,b,cbox.score.Chinese=80
box.score.math=100
box.score.English=90
// src/main/resource/META-INF/spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.fig.BoxPropertyConfig
  • 可以实现 TestProperty Bean的属性注入。
  • 同时可以在 l 或者 l 定义同名属性进行 值的覆盖。
  • 通过注解@PropertySource导入进来的属性源的优先级是最低的。

动态更新

若系统接入Apollo,使用Apollo进行动态更新属性值,不生效,原因在于 @ConfigurationProperties 目前不支持属性值的热更新。

法一:

可以考虑使用 @Value 进行属性注入,能够实现 动态更新属性值。

法二:

创建 ApolloConfigChangeListener ,发布环境变量变更Event。
@Component
public class ApolloConfig implements ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}@ApolloConfigChangeListenerprivate void someOnChange(ConfigChangeEvent changeEvent) {Set<String> changedKeys = changeEvent.changedKeys();changedKeys.forEach(k -> {ConfigChange change = Change(k);log.String());});// 更新@ConfigurationProperties注解的beanthis.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));}
}

参考

本文发布于:2024-02-08 19:53:59,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170739339968541.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:PropertySource
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23