@Autowired Bean Assignment in Constructor
A common issue encountered when using @Autowired beans is that they may initially be null when referenced in a constructor. This article explores this behavior and provides a solution to address it.
In the provided code snippet, the @Autowired bean applicationProperties is null when accessed in the DocumentManager constructor, but it's correctly initialized when referenced in other methods. This inconsistency arises due to the lifecycle of bean initialization.
Autowiring of beans occurs after object construction, meaning they are not yet assigned values when the constructor is called. To resolve this, move the initialization logic to a separate method annotated with @PostConstruct. This annotation ensures that the method is invoked after bean instantiation and dependency injection, allowing you to reliably access autowired beans.
Revised Code Snippet
public class DocumentManager implements IDocumentManager { @Autowired private IApplicationProperties applicationProperties; public DocumentManager() { } @PostConstruct public void init() { startOOServer(); } private void startOOServer() { if (applicationProperties != null) { ... } } }
With this modification, the initialization code will run after the object's construction and ensure that the applicationProperties bean is available when required in the DocumentManager.
The above is the detailed content of Why is my @Autowired bean null in the constructor but not in other methods?. For more information, please follow other related articles on the PHP Chinese website!