我的注释@Value 返回 null,即使它被使用并调用到组件注释类中 [英] My annotation @Value return null even it being used and called into component annotated classes

查看:17
本文介绍了我的注释@Value 返回 null,即使它被使用并调用到组件注释类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring,需要一些帮助:我想使用 application.properties 而不是硬编码来设置一个 API 密钥,但它总是返回 null.IntelliJ 将其正确评估为我在文件中设置的值.我已经在这里阅读了其他问题,几乎所有的解决方案都说 Spring 只能注入"托管类中的那些值注释,如组件、Beans 等.这就是(认为)我所做的,但仍然为空!其他一切都按我的预期工作.任何方向表示赞赏!

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) 字段在构造函数中将始终为空.将 @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆