Home >Java >javaTutorial >Why Are @Autowired Beans Null in Constructors?
In Java-based Spring applications, @Autowired dependencies are typically injected after bean instantiation. This means that if you reference an @Autowired bean in a constructor, it will be null.
In the provided code snippet, you attempt to use the @Autowired applicationProperties bean in the DocumentManager constructor, but it initially returns null. This is expected behavior because @Autowired beans are not yet available during construction.
To circumvent this issue, consider moving any initialization logic that depends on @Autowired beans to a separate post-construction method annotated with @PostConstruct. The @PostConstruct method is executed after bean instantiation and before the bean is ready for use.
In the corrected code below, the startOOServer() method has been moved to a @PostConstruct method:
@Component public class DocumentManager implements IDocumentManager { private Log logger = LogFactory.getLog(this.getClass()); private OfficeManager officeManager = null; private ConverterService converterService = null; @Autowired private IApplicationProperties applicationProperties; // Constructors may not access @Autowired beans, so move this logic to a @PostConstruct method public DocumentManager() { } @PostConstruct public void startOOServer() { if (applicationProperties != null) { if (applicationProperties.getStartOOServer()) { try { if (this.officeManager == null) { this.officeManager = new DefaultOfficeManagerConfiguration() .buildOfficeManager(); this.officeManager.start(); this.converterService = new ConverterService(this.officeManager); } } catch (Throwable e){ logger.error(e); } } } } public byte[] convert(byte[] inputData, String sourceExtension, String targetExtension) { byte[] result = null; startOOServer(); ... }
By using the @PostConstruct method, initialization code can now safely rely on @Autowired dependencies being available.
The above is the detailed content of Why Are @Autowired Beans Null in Constructors?. For more information, please follow other related articles on the PHP Chinese website!