spring
spring copied to clipboard
Spring @EventListener support in component
@heruan commented on Wed Jan 03 2018
When building a PWA with Flow and Spring, I'd like my components able to react on server events using Spring's @EventListener
and @TransactionalEventListener
. For example:
@Route("users")
public class UserList extends Grid<User> {
// ...
@EventListener
public void onNewUser(NewUserEvent event) {
UI.getCurrent().access(getDataProvider()::refreshAll);
}
}
At the moment it seems like @EventListener
-annotated methods in @Route
-annotated components are not invoked when the observed event is published.
Is there a work around to make this work currently?
The problem here is that component instances are created at each page load, while event listeners are singletons. I still can't imagine how components might be also event listeners, and now I feel it could be an anti-pattern.
More than a workaround, I think it would be more correct to delegate the listener method to a singleton service (i.e. a Spring @Service
bean) and "subscribe" the component to the service.
I've currently implemented this using the Java Flow (not Vaadin's Flow 🙂) API, i.e. java.util.concurrent.Flow.Publisher
and java.util.concurrent.Flow.Subscriber
.
The problem here is that component instances are created at each page load, while event listeners are singletons. I still can't imagine how components might be also event listeners, and now I feel it could be an anti-pattern.
More than a workaround, I think it would be more correct to delegate the listener method to a singleton service (i.e. a Spring
@Service
bean) and "subscribe" the component to the service.I've currently implemented this using the Java Flow (not Vaadin's Flow 🙂) API, i.e.
java.util.concurrent.Flow.Publisher
andjava.util.concurrent.Flow.Subscriber
.
i am currently using googles EventBus, which does the job. But it's not recommended to use by the google devs. so i was looking for a simple alternative. do you have some code examples how to implement the "Flow.Subscriber" in a vaadin route?
Is there actually a workaround for this? It's still an issue today, what's the best practice for sending events to a view?
Seems like the Spring event listeners would be perfect to use with Vaadin
The problem here is that component instances are created at each page load, while event listeners are singletons.
@petersj-ess I think the ticket should be closed, as this is fundamentally just how Spring works. The solution is to use some EventBus instead of Spring events. Naturally use that EventBus as a proxy. I.e. listen Spring events elsewhere, and post another event to EventBus there and listen to EventBus in the view.