Spring @Value Annotation Injection Timing Issue

Spent 15 minutes wondering why my @Value annotation wasn't injecting the property. The code: @Component public class AppConfig {   @Value("${app . name}")   private String appName;   public AppConfig() {     System.out.println(appName);   } } It printed null every time. The problem: @Value injection happens after the constructor runs. In the constructor, Spring hasn't injected anything yet. The fix: Use @PostConstruct instead: @PostConstruct public void init() {   System.out.println(appName); } Or use constructor injection: public AppConfig(@Value("${app . name}") String appName) {   this.appName = appName; } Constructor runs first. Injection happens after. Simple timing issue. Easy to miss. #SpringBoot #Java #BackendDevelopment #Programming

Same thing applies to @Autowired fields. If you need them in the constructor, use constructor injection instead. Field injection happens after object creation.

Like
Reply

To view or add a comment, sign in

Explore content categories