亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

@Autowired bean在另一個bean的構造函數中引用時為null

@Autowired bean在另一個bean的構造函數中引用時為null

慕森卡 2019-08-19 15:49:08
@Autowired bean在另一個bean的構造函數中引用時為null下面顯示的是一段代碼,我嘗試引用我的ApplicationProperties bean。當我從構造函數引用它時它是null,但是當從另一個方法引用它時它很好。到目前為止,我在其他類中使用這個自動裝配的bean沒有任何問題。但這是我第一次嘗試在另一個類的構造函數中使用它。在下面的代碼片段中,當從構造函數調用時,applicationProperties為null,但在convert方法中引用時則不是。我錯過了什么@Componentpublic 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的s片段...@Componentpublic 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");   }
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

自動裝配在構造對象之后發生。因此,在構造函數完成之后才會設置它們。

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


查看完整回答
反對 回復 2019-08-19
?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

要在構造時注入依賴項,您需要將構造函數標記為@Autowiredannoation。

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


查看完整回答
反對 回復 2019-08-19
  • 2 回答
  • 0 關注
  • 1440 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號