The Navigation Lifecycle in the Vaadin 14 manual says:
It is also possible to register a standalone listener for this event using the
addBeforeEnterListener(BeforeEnterListener)
method inUI
.
But in modern Vaadin with the routing feature, we are no longer supposed to be writing a UI
subsclass. My rough understanding is that there is indeed a UI
object automatically instantiated for us, and then routing automatically replaces the content within that UI
object. So the existence of a UI
object is supposed to be transparent to us programmers using Vaadin Flow.
➥ So what is the lifecycle hook on a new UI
instance so I can write a user-authentication check as a BeforeEnterListener
to work globally across all my @Route
views?
Calling UI.getCurrent
will not do, as I would need to call that from somewhere in my layouts, but I am trying to register a listener before my layouts exist.
To hook into UI init, there is the UIInitListener
.
A
UIInitListener
can be used to receive an event each time a new UI has been created and initialized.The ideal place to add UIInitListeners would be inside a
VaadinServiceInitListener
E.g. with Springboot:
@Bean
VaadinServiceInitListener vaadinServiceInitListener() {
return new VaadinServiceInitListener() {
@Override
public void serviceInit(ServiceInitEvent serviceInitEvent) {
serviceInitEvent.getSource().addUIInitListener( initEvent -> System.out.println("UI Init for " + initEvent.getUI()));
}
};
}