【发布时间】:2016-03-18 04:20:40
【问题描述】:
在调用自动装配对象上的方法时,我在 Spring 应用程序中遇到 NullPointerException。有问题的类如下所示:
@Component
public class Listener {
@Autowired
TemplateService templateService;
@Async
@EventListener
private Future<String> listener1(Event1 event) {
System.out.println(templateService);
return new AsyncResult<>(null);
}
@Async
@EventListener
public Future<String> listener2(Event2 event) {
System.out.println(templateService);
return new AsyncResult<>(null);
}
}
当我发布触发listener1 的事件时,会打印null 值,但是当我发布触发listener2 的事件时,会调用TemplateService 的toString() 方法(如我所料)。我可能误解了@Async 如何影响@Autowired 对象的某些方面,但我无法确定那会是什么。我在滥用@Async 吗?我是否误解了如何在多线程环境中使用 @Autowired 对象?
【问题讨论】:
-
您的类没有实现接口,这意味着它不能被考虑用于类路径扫描。你没有滥用异步。
-
@JamesENL 我不确定你的意思。 templateService 连接在 listener2 中,因此 Spring 上下文必须知道该类。我要实现什么接口?
-
你的监听器上没有接口,所以 Spring 不知道它是一个类,也不能创建一个代理来创建 Async 方法。
-
@JamesENL 我真的不明白你的意思。你是说Spring只能知道实现any接口的类?
-
默认情况下是的(有办法绕过它,但这不相关),你需要有一个接口,它应该定义这个类应该实现的 listener1 和 listener2。
标签: spring multithreading asynchronous autowired