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

img

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_NAMEjava

© 著做权归做者全部,转载或内容合做请联系做者面试

img

将 HTML 转化为 PDF新姿式spring

Java 使用 UnixSocket 调用 Docker APIjson

Fastjson致命缺陷segmentfault

Service Mesh - gRPC 本地联调远程服务app

使用 Thymeleaf 动态渲染 HTML框架

Fastjson致命缺陷spa

Spring Boot 2 集成log4j2日志框架命令行

Java面试通关要点汇总集之核心篇参考答案3d

Java面试通关要点汇总集之框架篇参考答案

Spring Security 实战干货:如何保护用户密码

Spring Boot RabbitMQ - 优先级队列

img

本文由博客一文多发平台 OpenWrite 发布!
相关文章
相关标签/搜索