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

dre*_*nda 12 java spring spring-bean spring-boot spring-properties

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

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

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

你有什么建议吗?

Evg*_*rov 31

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

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

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

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

  • 然后尝试使用@PostConstruct方法 (2认同)

Efe*_*man 0

你有没有尝试过:

@Component
@PropertySource("file:/your/file/path")
public class MyBean {

  private @Value("${property}") String property;
  ...
}
Run Code Online (Sandbox Code Playgroud)