Jon*_*ams 10 java spring-boot application.properties
我想使用application.properties文件中的值,以便在另一个类的方法中传递它.问题是值总是返回NULL.可能是什么问题呢?提前致谢.
application.properties
filesystem.directory=temp
Run Code Online (Sandbox Code Playgroud)
FileSystem.java
@Value("${filesystem.directory}")
private static String directory;
Run Code Online (Sandbox Code Playgroud)
Plo*_*log 20
你不能在静态变量上使用@Value.您必须将其标记为非静态,或者在此处查看将值注入静态变量的方法:
https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/
编辑:以防万一将来链接中断.您可以通过为静态变量创建非静态setter来完成此操作:
@Component
public class MyComponent {
private static String directory;
@Value("${filesystem.directory}")
public void setDirectory(String value) {
this.directory = value;
}
}
Run Code Online (Sandbox Code Playgroud)
该类需要是一个Spring bean,否则它将不会被实例化,并且Spring将无法访问setter.
对于在所有上述建议之后仍然面临问题的人,请确保在构建 bean 之前没有访问该变量。
那是:
而不是这样做:
@Component
public MyBean {
@Value("${properties.my-var}")
private String myVar;
private String anotherVar = foo(myVar); // <-- myVar here is still null!!!
}
Run Code Online (Sandbox Code Playgroud)
做这个:
@Component
public MyBean {
@Value("${properties.my-var}")
private String myVar;
private String anotherVar;
@PostConstruct
public void postConstruct(){
anotherVar = foo(myVar); // <-- using myVar after the bean construction
}
}
Run Code Online (Sandbox Code Playgroud)
希望这会帮助某人避免浪费时间。
对于 OP,其他答案可能是正确的。
但是,我遇到了相同的症状( - 带@Value注释的字段是null),但有一个不同的潜在问题:
import com.google.api.client.util.Value;
确保您正在导入正确的@Value注释类!尤其是在当今 IDE 的便利下,这是一个非常容易犯的错误(我使用的是 IntelliJ,如果您在没有阅读自动导入的内容的情况下过快地自动导入,您可能会像我一样浪费几个小时)。
当然,要导入的正确类是:
import org.springframework.beans.factory.annotation.Value;
除了@Plog的答案外,您无需再进行检查。
static变量不能注入值。检查@Plog的答案。
@Component或注释课程@Service| 归档时间: |
|
| 查看次数: |
15942 次 |
| 最近记录: |