Spring Boot:@Value始终返回null [英] Spring Boot: @Value returns always null
问题描述
我想使用application.properties
文件中的值,以便在另一个类的方法中传递它.问题在于该值始终返回NULL
.可能是什么问题呢?预先感谢.
I would like to use a value from application.properties
file in order to pass it in the method in another class. The problem is that the value returns always NULL
. What could be the problem? Thanks in advance.
application.properties
application.properties
filesystem.directory=temp
FileSystem.java
FileSystem.java
@Value("${filesystem.directory}")
private static String directory;
推荐答案
您不能在静态变量上使用@Value.您必须将其标记为非静态,或者在此处查看将值注入静态变量的方法:
You can't use @Value on static variables. You'll have to either mark it as non static or have a look here at a way to inject values into static variables:
https://www.mkyong.com/spring/spring-inject-a-value-to-staticvariables/
以防万一将来链接中断.您可以通过为静态变量设置一个非静态设置器来实现此目的:
Just in case the link breaks in the future. You can do this by making a non static setter for your static variable:
@Component
public class MyComponent {
private static String directory;
@Value("${filesystem.directory}")
public void setDirectory(String value) {
this.directory = value;
}
}
该类必须是Spring Bean,否则它将不会被实例化,并且Spring将无法访问setter.
The class needs to be a Spring bean though or else it won't be instantiated and the setter will be not be accessible by Spring.
这篇关于Spring Boot:@Value始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!