弹簧靴:@Value始终返回空

我想使用文件中的值,以便在另一个类的方法中传递它。问题是该值始终返回。可能是什么问题?提前致谢。application.propertiesNULL

application.properties

filesystem.directory=temp

FileSystem.java

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

答案 1

不能对静态变量使用@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,否则它不会被实例化,并且Spring将无法访问setter。


答案 2

对于在完成上述所有建议后仍面临问题的用户,请确保在构造 Bean 之前未访问该变量。

那是:

而不是这样做:

@Component
public MyBean {
   @Value("${properties.my-var}")
   private String myVar;

   private String anotherVar = foo(myVar); // <-- myVar here is still null!!!
}

这样做:

@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
   }
}

希望这将有助于某人避免浪费时间。


推荐