springboot Java中读取配置文件中的内容,并将其赋值给静态变量的方法

提前: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);
    }

}

亲测可用。


版权声明:本文为IBMAM_Zoey原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。