This article shares the specific code of spring boot static variable injection configuration file for your reference. The specific content is as follows
spring static variable injection
Injection of static variable values directly in spring is not supported. Let's take a look at the code:
@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; }}The configuration file is as follows:
baseConfig: logBrokerList: 10.10.2.154:9092 logTopic: test monitorTopic: monitor
Use logBrokerList variable when project starts
@SpringBootApplicationpublic class Application {public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args);System.out.println("config static test :" + KafkaConfig.getLogBrokerList());}}Execution results:
config static test: null
Solution
Using spring's set injection method, inject static variables through non-static setter methods. We can change it to this way the static variables can obtain the information you configured:
@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;}}Execution results:
config static test :10.10.2.154:9092
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.