spring boot静态变量注入配置文件 spring boot静态变量注入配置文件详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring boot静态变量注入配置文件 spring boot静态变量注入配置文件详解

kongrun12   2021-03-28 我要评论
想了解spring boot静态变量注入配置文件详解的相关内容吗,kongrun12在本文为您仔细讲解spring boot静态变量注入配置文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,boot静态变量注入配置文件,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变量

@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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们