Home > Java > javaTutorial > Why Are @Autowired Beans Null in Constructors?

Why Are @Autowired Beans Null in Constructors?

DDD
Release: 2024-11-20 04:17:01
Original
328 people have browsed it

Why Are @Autowired Beans Null in Constructors?

Understanding Null @Autowired Beans 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();
    ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template