Spring Boot with Vaadin Applications - @Route @Component Example

Let’s take a look at a concrete example. Below, we create a view by mapping a VerticalLayout component to the contacts path. We use Spring to inject a service class into the constructor for backend access. We then instantiate a Vaadin Grid component and pass in a list of Contact objects to the grid. Finally, we add an H1 header and the grid to our view to display them.

@Route("contacts") // localhost:8080/contacts
public class ContactsView extends VerticalLayout {

 // Autowire a Spring @Service
 public VaadinView(ContactService service) {

   // Instantiate Vaadin data grid component
   Grid<Contact> grid = new Grid<>(Contact.class);

   // Pass in a list of Contacts to show in the grid
   grid.setItems(service.findAll());
 
   // Define columns
   grid.addColumn(Contact::getFirstName).setHeader("First Name");
   grid.addColumn(Contact::getLastName).setHeader("Last Name");
   grid.addColumn(Contact::getEmail).setHeader("Email");
   grid.addColumn(contact -> contact.getCompany().getName()).setHeader("Company");

   // Add components to the layout to show them
   add(
       new H1("All contacts"),
       grid
   );
 }
}

In the example above, @Route is a specialized @Component that makes sure ContractsView is a regular Spring bean in the context.


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation