SpringBoot中怎么使用@Value为静态变量赋值
SpringBoot中怎么使用@Value为静态变量赋值,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
采用写法取配置的,但取到的是个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); } }
关于SpringBoot中怎么使用@Value为静态变量赋值问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。