本文實例為大家分享了spring boot靜態變量注入配置文件的具體代碼,供大家參考,具體內容如下
spring 靜態變量注入
spring 中不支持直接進行靜態變量值的注入,我們看一下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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; } } |
配置文件如下:
1
2
3
4
|
baseConfig: logBrokerList: 10.10 . 2.154 : 9092 logTopic: test monitorTopic: monitor |
項目啟動時使用 logBrokerList變量
1
2
3
4
5
6
7
|
@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方法注入靜態變量 ,我們可以改成這樣就靜態變量可以獲取到你配置的信息了:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/kongrun12/article/details/76246369