解决SpringBoot @Value对static属性无效(为null)情况


今天想像普通变量一样如下采用写法取配置的,但取到的是个null。。。

@Value("${test.appKey}")
private static String appKey;

才发现不能通过这种方式取配置来给static变量赋值

在网上搜索了一波,能够通过setter方法或通过中间变量赋值的方法来解决这个问题

我就采用了setter方法,代码如下:

private static String appKey;

@Value("${test.appKey}")
public void setAppKey(String appKey) {
    TestIt.appKey = appKey;
}

需要注意的是,要把setAppKey方法的static去掉(如果是采用idea中generate生成的setter方法,会跟变量一样带上static,这里要去掉)

就这么写完后,写一个测试类来简单测试一下是否可行:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "spring.config.location = classpath:application-dev.yml"})
public class TestIt {

    private static String appKey;

    @Value("${test.appKey}")
    public void setAppKey(String appKey) {
        TestIt.appKey = appKey;
    }

    @Test
    public void valueTest(){
        System.out.println("forTest:" + appKey);
    }

}

运行完成后能在控制台中找到forTest:后跟着的不是null即为成功(当然如果你存储的配置就是null串当我没说。。。)

 

学会积累,加油!!!

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM