Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - My annotation @Value return null even it being used and called into component annotated classes

I'm new to 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!

My application.properties

api.someapiservice.key=08e...f

Class that uses the properties value:

@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'
    ...
}

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;
}
question from:https://stackoverflow.com/questions/65877929/my-annotation-value-return-null-even-it-being-used-and-called-into-component-an

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...