2011-06-13 103 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

相关问题