虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > Java编程 > spring boot静态变量注入配置文件详解

spring boot静态变量注入配置文件详解
类别:Java编程   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了spring boot静态变量注入配置文件的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了spring boot静态变量注入配置文件的具体代码,供大家参考,具体内容如下

spring 静态变量注入

spring 中不支持直接进行静态变量值的注入,我们看一下代码:

    @Component(value = "KafkaConfig")@ConfigurationProperties(prefix = "baseConfig")public class KafkaConfig {
    private static String logBrokerList;
    public static String getLogBrokerList() {
    return logBrokerList;
    }
    public static void setLogBrokerList(String logBrokerList) {
    KafkaConfig.logBrokerList = logBrokerList;
    }
    }

配置文件如下:

    baseConfig: logBrokerList: 10.10.2.154:9092 logTopic: test monitorTopic: monitor

项目启动时使用 logBrokerList变量

    @SpringBootApplicationpublic class Application {
    public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
    System.out.println("config static test :" + KafkaConfig.getLogBrokerList());
    }
    }

执行结果:

config static test :null

解决办法

利用spring的set注入方法,通过非静态的setter方法注入静态变量 ,我们可以改成这样就静态变量可以获取到你配置的信息了:

    @Component(value = "KafkaConfig")@ConfigurationProperties(prefix = "baseConfig")public class KafkaConfig {
    private static String logBrokerList;
    public static String getLogBrokerList() {
    return logBrokerList;
    }
    @Value("${
    baseConfig.logBrokerList}
    ")public void setLogBrokerList(String logBrokerList) {
    KafkaConfig.logBrokerList = logBrokerList;
    }
    }

执行结果:

config static test :10.10.2.154:9092

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

  • spring boot 注入 property的三种方式(推荐)
  • SpringBoot下的值注入(推荐)
  • springboot注入servlet的方法
  • 详解SpringBoot中实现依赖注入功能
  • Spring boot将配置属性注入到bean类中
  • Spring boot工具类静态属性注入及多环境配置详解
相关热词搜索: spring boot静态变量注入配置文件 spring