Skip to content
javahacks.dev
Vaadin

How to Use Vaadin With Spring Boot for Full Stack Java Apps

Wire a Vaadin application into Spring Boot so views get services by constructor injection, with the right scopes, security and a production build.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the Vaadin, Spring Boot, OpenJDK, HTML5 and Spring logos.

Vaadin and Spring Boot fit together well, because a Vaadin view is Java code and a Spring service is Java code. The integration makes your views Spring beans, which removes most of the glue. This post sets up the project, injects a service into a view and covers scopes, security and packaging. For the view basics see the Vaadin tutorial; for the Spring Boot side, Spring Boot from first project to production.

Add Vaadin to a Spring Boot project

Generate a project with the Spring Initializr and add the Vaadin dependency, or add the starter to an existing one:

pom.xmlXML
<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>

Import the Vaadin BOM in dependencyManagement so versions line up. Check the current instructions in the Vaadin Spring documentation, because starter coordinates and Boot compatibility are tied to Vaadin versions.

Inject a service into a view

src/main/java/dev/javahacks/contacts/ContactView.javajava
@Route("")
public class ContactView extends VerticalLayout {

    private final ContactService contacts;

    public ContactView(ContactService contacts) {
        this.contacts = contacts;

        Grid<Contact> grid = new Grid<>(Contact.class, false);
        grid.addColumn(Contact::getName).setHeader("Name");
        grid.setItems(query -> contacts.page(query.getOffset(), query.getLimit()).stream());
        add(grid);
    }
}
java
@Service
class ContactService {
    // repository calls, validation, transactions
}

The route class is created by Spring for each navigation, so the constructor argument is resolved from the context. No @Autowired is needed with a single constructor, as explained in dependency injection. Keep SQL and business rules out of the view; a view that grows a JdbcTemplate is a view you cannot test without a browser.

Scopes for UI state

A view is created per navigation, which means its fields reset when the user navigates away and back. For state that should survive, use Vaadin's scopes:

ScopeLives for
@RouteScopeThe route chain currently shown
@UIScopeOne browser tab
@VaadinSessionScopeThe user session, shared by all tabs
java
@VaadinSessionScope
@SpringComponent
class ShoppingCart { /* per-user state */ }

Session-scoped beans live in server memory, so keep them small. How the server-side model works explains why.

Security

Spring Security integrates through a Vaadin base configuration that protects the Vaadin endpoints and static resources and lets you restrict views by role. A typical shape annotates views with a role check and sets a login view, and also secures service methods:

java
@Service
class AdminService {
    @PreAuthorize("hasRole('ADMIN')")
    public void purgeInactive() { /* ... */ }
}

Enable method security with @EnableMethodSecurity. A view guard keeps users from stumbling into screens, and the service check is what keeps the data safe. The exact configuration class changes between Vaadin versions, so follow the security chapter for yours.

Configuration

Vaadin properties live in application.properties under vaadin.*, for example vaadin.productionMode=true. Spring Boot properties such as server.port and the datasource apply as usual. Add spring-boot-devtools for restart on class changes.

Package it

Shell
./mvnw clean package -Pproduction
java -jar target/contacts-1.0.jar

The profile builds the frontend into the jar. If the deployed app shows a blank page, see the production build fix. Container images work as with any Spring Boot jar, with sticky sessions at the load balancer if you run several replicas.

A complete first view

A route class with an injected service is the whole pattern. Spring creates the view when the route is first visited, and Vaadin renders it:

java
@Route("customers")
@PageTitle("Customers")
@PermitAll
public class CustomerView extends VerticalLayout {

    public CustomerView(CustomerService service) {
        Grid<Customer> grid = new Grid<>(Customer.class, false);
        grid.addColumn(Customer::name).setHeader("Name");
        grid.addColumn(Customer::email).setHeader("Email");
        grid.setItems(query -> service
                .page(VaadinSpringDataHelpers.toSpringPageRequest(query))
                .stream());
        add(grid);
    }
}

The lazy setItems with a query callback fetches one page at a time as the user scrolls, so a table of a million rows costs one page of memory. Loading the whole list with setItems(service.findAll()) is the common mistake, and it puts the entire result set into the session of every user who opens the page.

Server push for live updates

A view that shows data changing on the server, such as a job's progress, needs push. Annotate the application shell class once:

java
@Push
@SpringBootApplication
public class ShopApplication implements AppShellConfigurator {
    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

Updates from another thread must go through ui.access, because the UI is not thread-safe:

java
ui.access(() -> progress.setValue(done / total));

A callback that touches components without access fails with an IllegalStateException about the session lock, and a UI that has been closed throws on access, so detach the listener in onDetach. Each push connection is held open per browser tab, so plan the thread and connection capacity of the server for the number of users online at once.

The production build is a separate step

Development mode serves resources through a dev server and compiles the front end on the fly. A deployment needs the optimised bundle, which the Maven profile builds:

Shell
./mvnw -Pproduction clean package
java -jar target/shop-0.0.1.jar

A jar built without the profile starts in development mode on a server, reports a missing front-end bundle, or tries to start node and fails. The production profile needs Node.js available at build time, and downloads one if it is missing, so a build machine with no internet needs it installed ahead of time. Check the startup log for Vaadin is running in production mode.

Memory and sessions

Each user's open views and components live in the HTTP session, so memory grows with users and with the amount of data each view holds. A server for 500 concurrent users with 2 MB per session needs a gigabyte for sessions alone. Keep views light by paging data, releasing references in onDetach, and avoiding large objects as view fields. Set a session timeout that matches real use, and remember that a heartbeat from an open tab keeps the session alive for as long as the tab stays open.

ConcernSetting or habit
Sessions growingLower server.servlet.session.timeout, close idle tabs with a heartbeat limit
Slow first loadUse the production bundle and enable compression
Many users, one nodeSize heap per session, or use sticky sessions behind a balancer
SecurityExtend VaadinWebSecurity and annotate views with @RolesAllowed
Testing viewsUse a UI unit-test library such as Karibu Testing, plus TestBench for end-to-end

A load balancer needs sticky sessions, since the component tree lives in memory on one node. Session replication of a Vaadin UI is possible and costly, so most deployments pin a user to a node and accept that a restart logs them out.

Testing views without a browser

A Vaadin view can be tested in plain JUnit with a library that simulates the UI, such as Karibu Testing, which creates the components in the server JVM and lets a test click buttons and read grids. These tests run in milliseconds, so there can be hundreds of them. Reserve browser tests with TestBench for a few end-to-end flows, such as login and the main purchase path, because they are slow and sensitive to layout.

Test the services behind the views directly as well. A view that only calls a service is simple, and most bugs live in the service, where a normal unit test finds them quickly.

Where this does not apply

If your team already has a Spring REST API and a separate frontend, adding Vaadin only for admin screens in the same application is reasonable, and building a full Vaadin UI over an existing REST API duplicates logic. Reactive Spring WebFlux applications are not supported by Vaadin Flow, which runs on the Servlet stack. The Vaadin Spring Boot guide and the Spring Boot reference are the primary sources.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.