Spring Boot:@Value总是返回null

问题描述:

我想使用application.properties文件中的值,以便将它传递给另一个类中的方法。问题是该值始终返回NULL。可能是什么问题呢?提前致谢。Spring Boot:@Value总是返回null

application.properties

filesystem.directory=temp 

FileSystem.java

@Value("${filesystem.directory}") 
private static String directory; 

不能在静态变量使用@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; 
    } 
} 

类需要虽然是一个Spring bean,否则它将不会被实例化和setter方法将被Spring无法访问。

+0

感谢您的答复,但它仍然打印空值。 –

+0

@JonathanWilliams是Spring bean中的成员变量? “@ Value”注释只适用于Spring bean,不适用于任何其他Java类。 – Jesper

+0

我做了一些编辑。你的班是Spring bean吗?即它是用@Component注释的吗? – Plog

除了@ Plog的回答之外,还有几件事情可以与你交叉检查。

static变量不能被赋值。检查@ Plog的答案。

  • 确保类与@Component@Service
  • 组件扫描注释应该扫描封闭包注册豆。如果启用xml配置,请检查您的XML。
  • 检查属性文件的路径是否正确或在类路径中。