Java 无法使用多个spring事件侦听器实例
我试图熟悉java中的spring事件监听器,我遇到了奇怪的行为。 我有一个publisher类和一个listener类,我正在尝试使用同一个listener类的多个实例(不知道是否可能)。 这是我的密码:Java 无法使用多个spring事件侦听器实例,java,spring,events,event-handling,Java,Spring,Events,Event Handling,我试图熟悉java中的spring事件监听器,我遇到了奇怪的行为。 我有一个publisher类和一个listener类,我正在尝试使用同一个listener类的多个实例(不知道是否可能)。 这是我的密码: public class TestClass { public static void main(String[] args) throws Exception { testEvents(); } private static void testE
public class TestClass {
public static void main(String[] args) throws Exception {
testEvents();
}
private static void testEvents() throws InterruptedException {
AnnotationConfigApplicationContext eventPublisherContext = new AnnotationConfigApplicationContext(EventListenerConfig.class);
CustomSpringEventPublisher eventPublisher = eventPublisherContext.getBean(CustomSpringEventPublisher.class);
List<CustomSpringEventListener> listenersList = new ArrayList<CustomSpringEventListener>();
for (int i = 0; i < 5; i++) {
listenersList.add(i, new CustomSpringEventListener());
}
for (int i = 0; i < 10; i++) {
Thread.sleep(5000);
LocalDateTime now = LocalDateTime.now();
eventPublisher.doStuffAndPublishAnEvent("new event " + now.format(Formats.isolong));
}
}
}
我的配置类如下所示:
@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
@Override
public void onApplicationEvent(CustomSpringEvent event) {
System.out.println("Received spring custom event - " + event.getMessage());
}
}
@Component
public class CustomSpringEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void doStuffAndPublishAnEvent(final String message) {
System.out.println("Publishing custom event --> " + message);
this.applicationEventPublisher.publishEvent(new CustomSpringEvent(this, message));
}
}
@Configuration
@ComponentScan({"some.local.directory"})
public class EventListenerConfig {
}
我希望这段代码的输出将是一次发布,然后是5次接收。然而,实际产出是:
Publishing custom event --> new event 2020-02-17T08:07:03.349
Received spring custom event - new event 2020-02-17T08:07:03.349
Publishing custom event --> new event 2020-02-17T08:07:08.389
Received spring custom event - new event 2020-02-17T08:07:08.389
Publishing custom event --> new event 2020-02-17T08:07:13.403
Received spring custom event - new event 2020-02-17T08:07:13.403
似乎忽略了for
循环,在该循环中,我将同一侦听器的新实例添加到列表中。为什么会这样?甚至可以创建同一侦听器的多个实例并让它们接收已发布的事件吗?如何修改代码使其工作?如果我尝试在多个线程中实例化同一个侦听器,它们中只有一个会响应该事件,会发生什么?
任何帮助都将不胜感激,谢谢。我不会。您正在应用程序上下文之外创建实例。Spring对这些事件侦听器一无所知,所以他们不会做任何事情。那么我应该怎么做才能让它工作呢?在应用程序上下文中将它们注册为bean。你能更具体一点吗?登记谁?事件侦听器已注册为组件,我只想创建它的几个实例。@组件将一个bean添加到应用程序上下文中。当您使用
.getBean(…)
时,您可以从上下文中获得这个特定的bean。因此,目前在您的上下文中有一个侦听器和一个发布器。如果要以编程方式添加更多侦听器,可以通过applicationContext.registerBean(…)
(或类似工具)来实现。不过,我建议您看看spring集成。您可能需要的都有(例如集成流生成器)。