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

9次阅读

共计 971 个字符,预计需要花费 3 分钟才能阅读完成。

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

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

● 将 HTML 转化为 PDF 新姿势

● Java 使用 UnixSocket 调用 Docker API

● Fastjson 致命缺陷

● Service Mesh – gRPC 本地联调远程服务

● 使用 Thymeleaf 动态渲染 HTML

● Fastjson 致命缺陷

● Spring Boot 2 集成 log4j2 日志框架

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

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

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

● Spring Boot RabbitMQ – 优先级队列

本文由博客一文多发平台 OpenWrite 发布!

正文完
 0