Spring @Value(“$ {}”)通常为null

我正在使用Spring Boot应用程序。 在某些@Component类中,加载@Value字段,而不是在其他类上,它们始终为null

似乎在创建@Bean / @Component后加载了@Bean

我需要从@Bean的属性文件加载一些值。

你有什么建议吗?

在构造bean(执行构造函数)之后注入属性(以及所有bean依赖项)。

如果需要,可以使用构造函数注入。

 @Component public class SomeBean { private String prop; @Autowired public SomeBean(@Value("${some.prop}") String prop) { this.prop = prop; //use it here } } 

另一种选择是在使用@PostConstruct注释的方法中移动构造函数逻辑,它将在创建bean之后执行,并且所有它的依赖项和属性值都将被解析。

你有没有尝试过:

 @Component @PropertySource("file:/your/file/path") public class MyBean { private @Value("${property}") String property; ... } 

另一个可能的原因是’@Value’行低于需要这些属性/值的行。

我花了很多时间调试这个问题,发现行的顺序很重要!