@Autowired bean is null when referenced in the constructor of another bean

Autowiring (link from Dunes comment) happens after the construction of an object. Therefore they will not be set until after the constructor has completed.

If you need to run some initialization code, you should be able to pull the code in the constructor into a method, and annotate that method with @PostConstruct.


Yes, both answers are correct.

To be honest, this problem is actually similar to the post Why is my Spring @Autowired field null? .

The root cause of the error can be explained in the Spring reference doc (Autowired) , as follow:

Autowired Fields

Fields are injected right after construction of a bean, before any config methods are invoked.

But the real reason behind this statement in Spring doc is the Lifecycle of Bean in Spring. This is part of Spring's design philosophy.

This is Spring Bean Lifecycle Overview: enter image description here Bean needs to be initialized first before it can be injected with properties such as field. This is how beans are designed, so this is the real reason.

I hope this answer is helpful to you!


To have dependencies injected at construction time you need to have your constructor marked with the @Autowired annoation like so.

@Autowired
public DocumentManager(IApplicationProperties applicationProperties) {
  this.applicationProperties = applicationProperties;
  startOOServer();
}