Blog

How to Build Java EE Web Apps with Vaadin Using CDI

By  
Johannes Häyry
Johannes Häyry
·
On Oct 25, 2018 9:00:00 AM
·

The Vaadin CDI add-on brings you Java EE web profile’s Contexts and Dependency Injection to Vaadin applications. With the Vaadin CDI add-on, you can turn your Vaadin UI views and components into CDI managed beans and start using @Inject in your route targets or layouts. Taking the add-on into use means simply adding one dependency to your project in Vaadin 10 and later. The add-on is compatible with Java EE / Jakarta EE containers version 7 and newer.

To enable CDI features, you should use the automatically deployed CDI enabled Vaadin servlet com.vaadin.cdi.CdiVaadinServlet. Defining a custom servlet is only needed if you want to do some particular configuration. Most of the components instantiated by Vaadin Flow become managed beans ( full-fledged CDI contextual instances ). They are queried from CDI BeanManager by the add-on, and all of the CDI features are usable.

Summarized, here are the Vaadin CDI features that boost your Vaadin app development experience on Java EE:

  • Custom contexts for Vaadin Service, Session, UI, and Router
  • Use @Inject in your route targets and layouts
  • Components injected into polymer template classes by @id become managed beans.
  • Some of the Vaadin service interfaces like I18NProvider can be implemented as a CDI bean.
  • Many of the Vaadin events are fired as CDI events, e.g. BeforeEnterEvent and BeforeLeaveEvent.

Vaadin CDI is likely to be included in Vaadin 12, which is two weeks away from beta, but the CDI module itself is already stable and fully compatible with Vaadin 10 and 11. All you have to do is add the following into your pom.xml.

<dependency>
   <groupId>com.vaadin</groupId>
   <artifactId>vaadin-cdi</artifactId>
   <version>10.0.0</version>
</dependency>
	

To quickly create a new project using the Vaadin platform and CDI, use the Project Base for Vaadin Flow and CDI. If you are new to developing with Vaadin on Java EE, or you want to check how the new platform version compares to previous Vaadin 7 and 8 versions, I recommend starting with this Vaadin CDI tutorial.

Johannes Häyry
Johannes Häyry
I'm a developer disguised as a product marketer. I usually write about new Vaadin releases or the upcoming cool features on the roadmap.
Other posts by Johannes Häyry