使用@Scheduled注释时,自动连接的条目是否为空?

时间:2016-01-28 22:23:50

标签: spring spring-4

Spring版本4.2.0.RELEASE

给定以下类,当spring执行cleanDocumentMirror方法时,config成员变为null。我的代码基本上类似于spring example。它不仅仅是这个字段,而且所有其他自动连接的字段都是空的。

我有afterPropertiesSet方法,该方法指的是config成员,它没有失败,或者在其他方面成员是自动连线的。应用程序确实正确启动并且正常工作,因为所有依赖项都已正确注入。只有在调用此方法时,我才会将所有自动连接的条目视为空。

该类有一些带@JmsListener注释的方法,当spring调用这些方法时,成员看起来是正确的。只有在调用预定方法时,我才会遇到问题。所以我可能需要启用一些设置。

@Component
@Scope("singleton")
@Transactional(value = "somevalue")
@EnableTransactionManagement()
public class DownloadResponseListener implements InitializingBean {
     @Autowired
     AggregatorConfig config;

  @JmsListener(destination = "response_queue", containerFactory = "mqConnectionContainerFactory") 
public void process(final ObjectMessage message) {
    config.getConfigrationValue(); // works correctly here.
    }

  @Scheduled(fixedRate = 5 * 1000)
  void cleanDocumentMirror() {
       config.getConfigrationValue(); // causes NPE here as config is null
  }
}

2 个答案:

答案 0 :(得分:4)

我有同样的问题。我发现在添加@Scheduled注释之后,Spring实际上创建了两次bean - 一次正确,一次没有任何依赖项,这是由任务调度程序执行的。

在我的情况下,这是因为用@Scheduled注释的方法是最终的,我想这引起了Spring的自动代理机制的问题。

尝试在代码中找到类似的原因,Spring可能无法正确代理该对象(如果在这种情况下引发错误甚至是警告,那将会很好!)。

答案 1 :(得分:0)

就我而言,该方法是程序包私有的。我必须将其公开,然后Spring才能正确注入依赖项。