简体   繁体   English

EventListener使Spring创建所有作用域bean

[英]EventListener makes Spring create all scoped beans

I have session scoped beans and want them to listen to events. 我有会话范围的bean,希望他们听事件。 For example 例如

@Component
@VaadinSessionScope
public class MyView {

    @EventListener
    public void onSearch(SearchEvent event) {
    }
}

The problem is if I add the @EventListener annotation all session scoped beans that are event listeners are created. 问题是如果我添加了@EventListener注释,那么创建了事件侦听器的所有会话作用域bean。

Is there a way to prevent creating beans and only send the event to already exisiting beans or can I register event handlers programmatically? 有没有办法阻止创建bean并只将事件发送到已经存在的bean或者我可以以编程方式注册事件处理程序吗?

I decided to go for a programmatic event handler registration. 我决定去编程事件处理程序注册。

You need the ApplicationEventMulticaster that you can inject: 您需要可以注入的ApplicationEventMulticaster:

@Autowired 
ApplicationEventMulticaster applicationEventMulticaster;

Then I hold a reference to a dynamically created EventListener : 然后我持有对动态创建的EventListener的引用:

private ApplicationListener<ApplicationEvent> applicationEventApplicationListener;

It's important to note that the class must not implement the ApplicationListener interface. 请务必注意,该类不得实现ApplicationListener接口。 That's the same as annotating a method with @EventListener and will leed to the unwanted bean creation. 这与使用@EventListener注释方法@EventListener ,并将导致不需要的bean创建。

private ApplicationListener<ApplicationEvent> createApplicationEventApplicationListener() {
     return event -> onApplicationEvent(event);
}

In my case when the component becomes visible I add the listener and when it's not visible I remove the listener: 在我的情况下,当组件变得可见时,我添加了监听器,当它不可见时,我删除了监听器:

if (visible) {
    if (applicationEventApplicationListener == null) {
        applicationEventApplicationListener = createApplicationEventApplicationListener();
    }
    applicationEventMulticaster.addApplicationListener(applicationEventApplicationListener);
} else {
    if (applicationEventApplicationListener != null) {
           applicationEventMulticaster.removeApplicationListener(applicationEventApplicationListener);
    }
}

That finally worked for me. 这最终对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM