gpt4 book ai didi

spring - 使用@Scheduled 注释时 Autowiring 的条目为空?

转载 作者:行者123 更新时间:2023-12-01 12:30:03 24 4
gpt4 key购买 nike

Spring 版 4.2.0.RELEASE

给定以下类,当 spring 执行 cleanDocumentMirror 方法时,配置成员变为空。我的代码本质上类似于 spring example .它不仅是这个字段,而且所有其他 Autowiring 的字段都是空的。

我有 afterPropertiesSet 方法,该方法指的是配置成员,它不会失败,或者换句话说,成员是自动正确连接的。由于正确注入(inject)了所有依赖项,应用程序确实可以正确启动并且可以正常工作。仅当调用此方法时,我才会看到所有 Autowiring 的条目为空。

该类有一些带有@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
}
}

最佳答案

我遇到过同样的问题。我发现在添加 @Scheduled 之后在注解中,Spring 实际上创建了 bean 两次——一次是正确的,一次是没有任何依赖关系的,这是由任务调度程序执行的。
在我的情况下,这是因为使用 @Scheduled 注释的方法是最终的,我想这会导致 Spring 的自动代理机制出现问题。
在 Kotlin 中,默认情况下所有类都是 final 的,因此这是一个常见问题。在 Kotlin 中使用 Spring 时,请考虑使用 kotlin-spring plugin自动将 Spring 注释的类和方法编译为 open .
尝试在您的代码中找到类似的原因,即 Spring 可能无法正确代理对象(如果它在这种情况下引发错误甚至警告,那就太好了!)。

关于spring - 使用@Scheduled 注释时 Autowiring 的条目为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35073303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com