Video in progress
Why does this code throw a NullPointerException?
@Component
public class SmsSender {
@Value("${sms.prefix}")
private String prefix;
private final String header;
public SmsSender() {
this.header = prefix.toUpperCase();
}
}
@Value is injected into the field after the object is created. While the constructor runs, prefix is still null. Take the value as a constructor parameter instead.
📖 Answer
Spring calls the constructor first and only then sets the fields. Inside the constructor prefix is still empty — null.toUpperCase() → NPE, and the app fails at startup.
The fix is simple:
@Component
public class SmsSender {
private final String header;
public SmsSender(@Value("${sms.prefix}") String prefix) {
this.header = prefix.toUpperCase();
}
}
Now Spring resolves the value before calling the constructor.
Moving it to @PostConstruct also works, but the constructor is better: the field stays final, and you don't have to think about ordering.
The same goes for @Autowired fields: inside the constructor they're still null.
Sign up to mark studied questions and save your progress.