@Autowired在另一个 Bean 的构造函数中引用时 bean 为 null

2022-08-31 10:21:23

下面显示的是一段代码,我尝试在其中引用我的 ApplicationProperties bean。当我从构造函数引用它时,它是空的,但是当从另一个方法引用时,它很好。到目前为止,我在其他类中使用这种自动连接的bean并没有遇到任何问题。但这是我第一次尝试在另一个类的构造函数中使用它。

在下面的代码片段中,当从构造函数调用时,属性为 null,但在 convert 方法中引用时,它不为 null。我错过了什么

@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;


  // If I try and use the Autowired applicationProperties bean in the constructor
  // it is null ?

  public DocumentManager() {
  startOOServer();
  }

  private 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();
    ...

以下是来自 ApplicationProperties 的片段 ...

@Component
public class ApplicationProperties implements IApplicationProperties {

  /* Use the appProperties bean defined in WEB-INF/applicationContext.xml
   * which in turn uses resources/server.properties
   */
  @Resource(name="appProperties")
  private Properties appProperties;

  public Boolean getStartOOServer() {
    String val = appProperties.getProperty("startOOServer", "false");
    if( val == null ) return false;
    val = val.trim();
    return val.equalsIgnoreCase("true") || val.equalsIgnoreCase("on") || val.equalsIgnoreCase("yes");
  }

答案 1

自动布线(来自沙丘注释的链接)发生在构建对象之后。因此,在构造函数完成之前不会设置它们。

如果需要运行一些初始化代码,则应该能够将构造函数中的代码提取到方法中,并使用@PostConstruct对该方法进行批注。


答案 2

要在构造时注入依赖项,您需要将构造函数标记为如下所示。@Autowired

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

推荐