2011-06-13 104 views
65

下面顯示的是代碼片段,我嘗試引用我的ApplicationProperties bean。當我從構造函數中引用它時,它是null,但是當從另一個方法引用時它就沒有問題。直到現在,我還沒有在其他類中使用這個autowired bean沒有問題。但這是我第一次嘗試在另一個類的構造函數中使用它。@Autowired bean在另一個bean的構造函數中引用時爲null

在構造函數中調用applicationProperties下的代碼片段時,如果在轉換方法中引用它,則不是。我缺少

@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"); 
    } 
+0

我們可以看到你的xml嗎? – Drahakar 2011-06-13 20:37:37

回答

129

Autowiring(從沙丘評論鏈接)對象的建設後,會發生。因此在構造函數完成之後纔會設置它們。

如果您需要運行一些初始化代碼,您應該能夠將構造函數中的代碼拖入方法中,並使用@PostConstruct對該方法進行註釋。

+3

正如它在文檔中所說 - http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html – Dunes 2011-06-13 20:38:42

+0

感謝您的鏈接,我會將其添加到答案中以便於查找。 – 2011-06-13 20:39:48

+2

謝謝你,我還沒有遇到這樣的重要陳述:「田地是在建造豆後立即注入的......」。我已經嘗試了@PostConstruct註釋,這正是我所需要的。 – hairyone 2011-06-13 20:59:47

28

要在構建時注入依賴項,您需要使用@Autowired這樣的annoation標記您的構造函數。

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

我還沒有嘗試過,但這看起來太棒了。 – asgs 2015-06-12 21:53:51

+1

其實我認爲這應該是首選的答案。基於構造函數的依賴注入方法非常適合於強制組件。使用這種方法,彈簧框架也將能夠檢測組件上的循環依賴關係(如A中取決於B,B取決於C,C取決於A)。 使用setter或autowired字段的注入風格能夠將不完全初始化的bean注入到您的字段中,使事情變得更加混亂。 – Seakayone 2016-01-11 08:49:49

相關問題