栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号