We need to override VaadinServlet, UIProvider and UI class to provide CDI support in Vaadin application.
Servlet Code
@WebServlet(urlPatterns = "/*")
public class Servlet extends VaadinServlet {
private static final long serialVersionUID = 2298654353565 L;
@Inject
private Instance applicationProvider;
@SuppressWarnings("serial")
private final SessionInitListener listener = new SessionInitListener() {
public void sessionInit(SessionInitEvent event) throws ServiceException {
event.getService();
final VaadinSession session = event.getSession();
session.addUIProvider(applicationProvider.get());
}
};
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
getService().addSessionInitListener(listener);
}
}
UI Provider
public class RootProvider extends UIProvider {
@Inject
private ApplicationUI rootProvider;
@Override
public UI createInstance(UICreateEvent event) {
return rootProvider;
}
@Override
public Class getUIClass(UIClassSelectionEvent event) {
return ApplicationUI.class;
}
}
view raw UIProvider.java hosted with ❤ by GitHub
UI
@Theme(ApplicationTheme.THEME_NAME)
@SessionScoped
public class ApplicationUI extends UI {
protected void init(VaadinRequest request) {
initialize(Locale.getDefault());
}
public void initialize(Locale locale) {
user.setLocale(locale);
addApplicationTitle();
VerticalLayout view = new VerticalLayout();
setContent(view);
view.setStyleName(ApplicationTheme.VIEW);
view.setWidth("100%");
view.setHeight("100%");
view.setSpacing(false);
view.setMargin(false);
Header header = CDIComponent.getInstance(Header.class);
view.addComponent(header);
header.addDefaultTab();
}
}
view raw UI.java hosted with ❤ by GitHub