Spring Boot:@Value返回null

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.


Phi*_*imo 8

对于在所有上述建议之后仍然面临问题的人,请确保在构建 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)

希望这会帮助某人避免浪费时间。

  • 这就是我的解决方案。我一直在构造函数中使用属性。所以我将 init 的东西移到 @PostConstruct 中并在那里初始化它们。 (3认同)

sco*_*eus 7

对于 OP,其他答案可能是正确的。

但是,我遇到了相同的症状( - 带@Value注释的字段是null),但有一个不同的潜在问题:

import com.google.api.client.util.Value;

确保您正在导入正确的@Value注释类!尤其是在当今 IDE 的便利下,这是一个非常容易犯的错误(我使用的是 IntelliJ,如果您在没有阅读自动导入的内容的情况下过快地自动导入,您可能会像我一样浪费几个小时)。

当然,要导入的正确类是:

import org.springframework.beans.factory.annotation.Value;


Kar*_*k R 5

除了@Plog的答案外,您无需再进行检查。

static变量不能注入值。检查@Plog的答案。

  • 确保使用@Component或注释课程@Service
  • 组件扫描应扫描随附的软件包以注册Bean。如果启用了xml,请检查您的XML。
  • 检查属性文件的路径是否正确或在classpath中。