一尘不染

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

spring

下面显示的是我尝试引用我的ApplicationProperties bean的代码片段。当我从构造函数引用它时,它为null,但是从另一个方法引用时,它很好。到目前为止,在其他类中使用此自动装配的bean都没有问题。但这是我第一次尝试在另一个类的构造函数中使用它。

在下面的代码段中,当从构造函数调用时,applicationProperties为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");
  }

阅读 790

收藏
2020-04-11

共1个答案

一尘不染

自动装配(link from Dunes commen)在构造对象之后发生。因此,直到构造函数完成后才设置它们。

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

2020-04-11