Spring Boot 注入外部配置到应用内部的静态变量

2019/10/25 06:30
阅读数 79
点击上方☝ 码农小胖哥 ,轻松关注!
及时获取有趣有料的技术文章

Spring Boot允许你外部化你的配置,这样你就可以在不同的环境中使用相同的应用程序代码,你可以使用properties文件、YAML文件、环境变量和命令行参数来外部化配置,属性值可以通过使用@Value注解直接注入到你的bean中,通过Spring的Environment抽象访问,或者通过@ConfigurationProperties绑定到结构化对象。那么如何进行Spring Boot 注入外部配置到应用内部的静态变量呢?操作如下:

属性配置类 StaticProperties.class

@Component
public class StaticProperties {

public static String CUSTOM_NAME;

@Value("${custom.name}")
public void setCustomName(String customName) {
CUSTOM_NAME = customName;
}

}

Spring Boot 配置提示 resources/META-INF/spring-configuration-metadata.json

{
"properties": [
{
"name": "custom.name",
"type": "java.lang.String",
"sourceType": "com.anoyi.xxx.config.StaticProperties"
}
]
}

Spring Boot 配置 application.properties

custom.name=anoyi

至此,即可在 Spring Boot 全局任意引用 StaticProperties.CUSTOM_NAME

© 著作权归作者所有,转载或内容合作请联系作者



本文分享自微信公众号 - 码农小胖哥(Felordcn)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部