为了账号安全,请及时绑定邮箱和手机立即绑定

@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 关注
  • 1353 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信