我的注解@Value返回null,即使它已被使用并调用到组件带注释的类中 [英] My annotation @Value return null even it being used and called into component annotated classes
问题描述
我正在使用Spring,需要一些帮助:我想使用application.properties设置一个API密钥,而不是对其进行硬编码,但是它始终返回null.IntelliJ将其正确评估为我在文件中设置的值.我已经在这里阅读了其他问题,几乎所有的解决方案都在说Spring只能注入"资源.托管类(例如,Components,Beans等)中的那些值注释.这就是(想想)我所做的,但仍然为null!其他一切都按我的预期工作.任何方向都值得赞赏!
I'm using Spring and need some help: I want to set one API key using application.properties instead of hardcoding it, but it always returns null. IntelliJ evaluates it correctly to the value I've set in the file. I've already read other questions here and almost all solutions are saying that Spring can only "inject" those value anotations in managed classes, like Components, Beans, etc. That's what (think) I did and still got null! Everything else is working as I intended. Any direction is appreciated!
我的application.properties
My application.properties
api.someapiservice.key=08e...f
使用属性值的类:
@Component
public class ApiClient implements ApiClientInterface {
@Value("${api.someapiservice.key}")
private String API_KEY;
public ApiClient () {
System.out.println(API_KEY); //Returns null after spring log info: Initialized JPA EntityManagerFactory for persistence unit 'default'
...
}
使用ApiClient的类:
Class that uses ApiClient:
@Component
public class SomeService {
private final SomeRepository someRepository;
private final ApiClient apiClient;
public PlaylistService(SomeRepository someRepository , ApiClient apiClient ) {
this.SomeRepository = SomeRepository;
this.apiClient = ApiClient;
}
推荐答案
在实例被构造好之后才可能进行字段注入,因此您的 @Value
(或 @Autowired
)字段在构造函数中始终为null.将 @Value
移至构造函数参数.
Field injection can't possibly happen until after the instance is already constructed, so your @Value
(or @Autowired
) fields will always be null in the constructor. Move the @Value
to a constructor parameter instead.
这篇关于我的注解@Value返回null,即使它已被使用并调用到组件带注释的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!