Documentation versions (currently viewingVaadin 23)

You are viewing documentation for Vaadin 23. View latest documentation

Component Lifecycle Callbacks

Reacting when your component is attached to or detached from the application.

If the content of a component depends on resources that aren’t available during the construction of the component, you can postpone content creation until the component attaches to the UI. You do this by overriding the onAttach() method provided by the Component class.

Example: Overriding the onAttach() method.

public class UserNameLabel extends Component {

  protected void onAttach(AttachEvent attachEvent) {
    // user name can be stored to session after login
    String userName = (String) attachEvent.getSession()
    getElement().setText("Hello " + userName +
            ", welcome back!");

The onAttach() method is invoked when the Component has attached to the UI. Its counterpart, the onDetach() method, is invoked right before the component detaches from the UI. These are good points at which to reserve and release resources used by the component.

Example: Overriding the onAttach() and onDetach() methods.

public class ShoppingCartSummaryLabel
        extends Component {

  private final Consumer<EventObject> eventHandler =

  protected void onAttach(AttachEvent attachEvent) {
    ShopEventBus eventBus = attachEvent.getSession()
    // registering to event bus for updates
    // from other components

  protected void onDetach(DetachEvent detachEvent) {
    ShopEventBus eventBus = detachEvent.getSession()
    // after detaching don't need any updates

  private void onCartSummaryUpdate(EventObject event) {
    // update cart summary ...

interface ShopEventBus {
  void register(Consumer<EventObject> eventHandler);

  void unregister(Consumer<EventObject> eventHandler);
  • Using methods available in attachEvent and detachEvent to get the UI or session is more convenient than using the getUI() method in Component, because these methods return values directly. The getUI() method returns an Optional<UI>, because a component isn’t always attached.

  • The default implementations of the onAttach() and onDetach() methods are empty, so you don’t need to call super.onAttach() or super.onDetach() from your overridden methods. However, when extending other component implementations, you may need to do this.

Finding out when another component is attached or detached
To find out when another component gets attached or detached, you can use the Component.addAttachListener() and Component.addDetachListener() methods. The corresponding events are fired after the onAttach() and onDetach() methods are invoked. The getUI() method for the component returns the UI instance during both events.