提前:springboot + dubbo微服务架构
在 组件服务 中需要获取配置文件并赋值给static修饰的变量方法
主要用到spring中的InitializingBean接口,重写afterPropertiesSet方法即可
具体代码:
1、在业务服务的application.properties中配置
data.test.value=这边是需要的值
2、 在组件服务中创建类,获取并重写afterPropertiesSet赋值到静态变量中
@Configuration
public class TestConstConfig implements InitializingBean {
/**
* 配置文件中的值
*/
@Value("${data.test.value}")
private String testValue;
/**
* 静态变量
*/
public static String constValue;
@Override
public void afterPropertiesSet() throws Exception {
constValue = this.testValue;
}
}
3、在spring.factories中配置TestConstConfig
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xx.xx.xx.TestConstConfig
4、如果其它类的静态方法中需要用到此配置值,直接调用即可
public class TestUtil{
public static void testConstMethod(){
System.out.println(TestConstConfig.constValue);
}
}
亲测可用。
本文介绍如何在SpringBoot结合Dubbo微服务架构中,通过InitializingBean接口实现配置文件动态赋值给静态变量。通过`@Value`注解读取`application.properties`中的配置,并在TestConstConfig类中进行设置。只需几步,即可让其他类无障碍访问配置值。
1348

被折叠的 条评论
为什么被折叠?



