Junior — Middle
What could be the reasons for NullPointerException when using dependency injection in Spring if the constructor is not used for injection?
sobes.tech AI
Answer from AI
NullPointerException when using dependency injection in Spring without a constructor usually occurs because the fields annotated with @Autowired were not properly initialized. Main reasons:
- The class is not a Spring Bean (not annotated with
@Component,@Service,@Repository, or not declared in configuration), so Spring does not manage its lifecycle and does not inject dependencies. - The object is created manually via
new, not through the Spring container, so autowiring does not happen. - The
@Autowiredannotation is missing or used incorrectly on the field. - Using
@Autowiredon private fields without proper configuration (although Spring can inject into private fields).
To avoid NullPointerException, ensure:
- The class is a Spring Bean.
- Use constructor injection — this is more reliable and recommended.
- If using field injection, ensure the object is created by Spring.
Example of correct field injection:
@Component
public class MyService {
@Autowired
private Dependency dependency;
public void doSomething() {
dependency.action();
}
}
If MyService is created via new MyService(), then dependency will be null, leading to NullPointerException when calling doSomething().