Spring @Value Injection Timing Issue

Spent 45 minutes wondering why my @Value annotation was returning null. The code looked fine: @Value("${api.key}") private String apiKey; public MyService() {   System.out.println(apiKey); // null } The problem: I was accessing the value inside the constructor. Spring injects @Value AFTER the object is created. Inside the constructor, it is always null. The fix: @Value("${api.key}") private String apiKey; @PostConstruct public void init() {   System.out.println(apiKey); // works } Use @PostConstruct if you need injected values during initialization. Constructor runs first. Injection happens after. What Spring Boot behavior surprised you when you first learned it? #Java #SpringBoot #Debugging #BackendDevelopment

This one confused me for a while. You assume everything is ready inside the constructor but Spring has not injected anything yet. @PostConstruct is the safe place for initialization logic.

Like
Reply

If you write a constructor inside a spring component, it does not get treated for DI by Spring, as Spring works on proxy creation

This is exactly why I prefer constructor injection over field injection in Spring.

Like
Reply

Well for peace of mind, the moment I mark a class with @Component or equivalent, I forget about contructors. Anything that needs to happen automatically -> use PostContruct or OnApplicationReady etc.

Like
Reply

Very useful insights and thanks for sharing.

See more comments

To view or add a comment, sign in

Explore content categories