zoukankan      html  css  js  c++  java
  • 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变量

    @SpringBootApplication
    public 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

  • 相关阅读:
    过河卒 NOIp 2002 dp
    [POI2014]KUR-Couriers BZOJ3524 主席树
    【模板】可持久化线段树 1(主席树)
    EXPEDI
    取石子游戏 BZOJ1874 博弈
    【模板】文艺平衡树(Splay) 区间翻转 BZOJ 3223
    关于表白
    POJ 1951
    Codeforces 1032F Vasya and Maximum Matching dp
    Codeforces 1016F Road Projects
  • 原文地址:https://www.cnblogs.com/pejsidney/p/9282506.html
Copyright © 2011-2022 走看看