春季版本 4.2.0.RELEASE
给定以下类,当 spring 执行 cleanDocumentMirror 方法时,config 成员变为 null。我的代码本质上类似于spring example。不仅仅是这个字段,所有其他自动装配字段都为空。
我有 afterPropertiesSet 方法,该方法引用配置成员,并且它不会失败,或者换句话说,成员会正确自动连接。由于所有依赖项均已正确注入,应用程序确实可以正确启动并正常工作。仅当调用此方法时,我才会看到所有自动装配的条目为空。
该类有一些带有@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
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到过同样的问题。我发现添加@Scheduled注释后,Spring 实际上创建了两次 bean —— 一次正确,一次没有任何依赖项,由任务调度程序执行。
就我而言,这是因为注释的方法@Scheduled是最终的,我猜这会导致 Spring 的自动代理机制出现问题。
在 Kotlin 中,默认情况下所有类都是最终类,因此这是一个常见问题。将 Spring 与 Kotlin 结合使用时,请考虑使用kotlin-spring 插件将 Spring 注解的类和方法自动编译为open.
尝试在代码中查找 Spring 可能无法正确代理对象的类似原因(如果在这种情况下引发错误甚至警告,那就太好了!)。
| 归档时间: |
|
| 查看次数: |
2747 次 |
| 最近记录: |