繁体   English   中英

Spring 引导:@Value 始终返回 null

[英]Spring Boot: @Value returns always null

我想使用application.properties文件中的值,以便在另一个 class 的方法中传递它。问题是该值始终返回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,否则它不会被实例化,并且 Spring 将无法访问 setter。

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

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

除了@Plog 的回答之外,您几乎没有什么需要交叉检查的。

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

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

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

但是,我遇到了相同的症状( @Value字段为null ),但存在不同的潜在问题:

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

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

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

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

Spring 使用依赖注入在找到 @Value 注释时填充特定值。 但是,它不是将值传递给实例变量,而是传递给隐式 setter。 然后这个 setter 处理我们的 NAME_STATIC 值的填充。

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

你可以利用这个。 参考评估(私有字符串 myVar)的值

this.myVar

将 @Autowired 注释添加到 class 的变量声明中。

@Autowired
private FileSystem  myFileSystem; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM