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
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.
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.
Very useful insights and thanks for sharing.
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.