Home > Java > javaTutorial > body text

Why is my @Autowired bean null in the constructor but not in other methods?

Linda Hamilton
Release: 2024-11-19 02:02:02
Original
803 people have browsed it

Why is my @Autowired bean null in the constructor but not in other methods?

@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) {
      ...
    }
  }
}
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template