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

点击上方☝码农小胖哥,轻松关注!
及时获取有趣有料的技术文章

640?wx_fmt=png

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

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

640?wx_fmt=png

640?wx_fmt=gif

原文地址:https://www.cnblogs.com/felordcn/p/12142530.html