Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
Vaadin7 + CDI
Hi guys,
is there already a way to use injection with vaadin 7?
I used this guide to do the CDI stuff with Vaadin 6.x
https://vaadin.com/wiki/-/wiki/Main/Creating%20JEE6%20Vaadin%20Applications
but now the entiy point is Root and not Application so there is no way to copy this guide to Vaadin 7 - any ideas?
Could I bump this question? Do all JEE6 CDI specs work in Vaadin? (Obviously only if Vaadin is hosted in a jee6 spec container.)
See: JSR-299 Spec
HI,
there are two projects that help you with CDI:
The great cdi-utils Addon https://vaadin.com/directory#addon/cdi-utils which shows you how to use CDI in Vaadin 6. Only Root Application acces has changed for Vaadin 7, main design will stay the same.
I have started with a CDI + Vaadin 7 based application framework which is just started and no official addon yet. You can find it here:
https://github.com/thomasletsch/javaee-addon
With a sample app here:
https://github.com/thomasletsch/javaee-addon-sample
In this application I use CDI with events, JPA 2. Tomi uses in his cdi-utils also custom scopes and so on. Since you program inside your container, everything will work until you start to work inside widgets.
Regards,
Thomas
You can find the default setup for V7 apps for CDI (as for V6) over here.
In the RootApplication you can define all of you beans.
The only change thereafter is then to change your Root to pick up the beans by using getApplication().get<yourBean>()
B)
? I don't get it - sorry!
Assuming that this is the basic we have:
public class MyApplicationRoot extends Root {
public static class RootApplication extends Application {
private static final long serialVersionUID = -1099516579868329607L;
@Override
protected Root getRoot(WrappedRequest request) throws RootRequiresMoreInformationException {
return new MyApplicationRoot();
}
}
@WebServlet(urlPatterns="/*")
public static class Servlet extends AbstractApplicationServlet {
private static final long serialVersionUID = -1386739418720898885L;
@Override
protected Application getNewApplication(HttpServletRequest request) throws ServletException {
return new RootApplication();
}
@Override
protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException {
return RootApplication.class;
}
}
private static final long serialVersionUID = 7428504147931595620L;
@Override
protected void init(WrappedRequest request) {
VerticalLayout view = new VerticalLayout();
view.addComponent(new Label("Hello Vaadin!"));
setContent(view);
}
}
how do we have to modify this code to enable CDI for at least the MyApplicationRoot class?
I just started a blog about Vaadin 7 and CDI (Guice here). Maybe this helps.
http://codeturm.blogspot.de/2012/08/eclipse-gae-guice-and-vaadin-7-part-one.html
and
http://codeturm.blogspot.de/2012/08/eclipse-gae-guice-and-vaadin-7-part-two.html
Have fun,
Christian
Also would like to note Adam Bien's Weblog about CDI and Vaadin.
http://www.adam-bien.com/roller/abien/entry/vaadin_java_ee_no_xml
Something similar should work with Vaadin 7 too .
I did this with Vaadin 6.8 and it works like a charm..
Hi there,
I tried to include Vaadin 7 beta 5 in a Multi-Module Maven Application with a war, jar and ear that will be deployed to JBoss AS 7.1.1.
So i tried following Code, but somehow CDI is not working.
The Variables that have @Inject are Null and i get a NullPointer Exception.
I have following FileStructure:
vaadin-war
- src/main/resources/WEB-INF
- beans.xml
- web.xml
and in the app-jar
- src/main/resources
- beans.xml
- persistence.xml (Hibernate)
Got follwongin Contents:
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
UIProvider
public class CdiUiProvider extends DefaultUIProvider implements Serializable{
private static final long serialVersionUID = 8043964411848504777L;
@Inject
private VaadinUI vaadinUI;
@Override
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
return VaadinUI.class;
}
@Override
public UI createInstance(UICreateEvent event) {
return vaadinUI;
}
}
My own CdiVaadinServlet
public class CdiVaadinServlet extends VaadinServlet{
private static final long serialVersionUID = -8833005846998449164L;
@Inject
private Instance<CdiUiProvider> applicationProvider;
@SuppressWarnings("serial")
private final SessionInitListener sessionInitListener = new SessionInitListener() {
@Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
@SuppressWarnings("unused")
VaadinService service = event.getService();
final VaadinServiceSession session = event.getSession();
session.addUIProvider(applicationProvider.get());
}
};
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
getService().addSessionInitListener(sessionInitListener);
}
}
The View
@Named
@ApplicationScoped
public class VaadinUI extends UI implements ClickListener {
private static final long serialVersionUID = 1L;
@Inject
private ShopUI shopUI;
@Override
protected void init(VaadinRequest request) {
buildMainLayout();
}
private void buildMainLayout() {
getPage().setTitle("Vaadin UI");
layout = new VerticalLayout();
layout.setSizeFull();
setComponent(shopUI);
setContent(layout);
}
}
problem is that shopUI is null and therefore nothing is set.
And also when i set a breakPoint in the Servlet nothing happens there so still think i ueses the Default-VaadinServlet instead of mine.
here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Vaadin Web Application</display-name>
<context-param>
<description>Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<servlet>
<servlet-name>Vaadin CDI Servlet</servlet-name>
<servlet-class>com.swissAs.htmlEval.vaadin.cdi.CdiVaadinServlet</servlet-class>
<init-param>
<description>Vaadin UI to display</description>
<param-name>UI</param-name>
<param-value>com.swissAs.htmlEval.vaadin.VaadinUI</param-value>
</init-param>
</servlet>
</web-app>
anybody an Idea what goes wrong?
I really would like to use jee6 as the backend, but that is useless if i can not inject the backend with the logic
Thanks
I also tried this GitHubProject without Luck
https://github.com/vaadin/vaadin-cdi-integration
anybody knows on how i have to config this one to get it wrork?
Sorry bit clueless here
found my Problem.
the Project had to web.xml, one under resources and one in webapp. deleted the resources one and configured the one in webapp. within the same war it works now.
only Injections to other jars are not working yet.
Hi Marc,
at the first glance your solution seems to work. But when I pressed "reload" in my browser and got an exception.
javax.servlet.ServletException: java.lang.IllegalStateException: UI id has already been defined
com.vaadin.server.VaadinServlet.handleServiceException(VaadinServlet.java:592)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:357)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:215)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
I am not sure whether it is correct to annotate the VaadinUI class as @ApplicationScoped, since Book of Vaadin states
[indent]"A Vaadin application is essentially a user session, and a session is created for each user who uses the application. In the context of our HelloWorld application, it is sufficient to know that the underlying session is created when the user first accesses the application by opening the page, and init() method is invoked at that time."[/indent]
I would assume @SessionScoped is more appropriate here but I get the same Exception when using it...
Sascha Kiedrowski: Hi Marc,
at the first glance your solution seems to work. But when I pressed "reload" in my browser and got an exception.
I am not sure whether it is correct to annotate the VaadinUI class as @ApplicationScoped, since Book of Vaadin states
[indent]"A Vaadin application is essentially a user session, and a session is created for each user who uses the application. In the context of our HelloWorld application, it is sufficient to know that the underlying session is created when the user first accesses the application by opening the page, and init() method is invoked at that time."[/indent]I would assume @SessionScoped is more appropriate here but I get the same Exception when using it...
I think @SessionScoped and @ApplicationScoped in vaadin 7 is more or less the same thing (Not identical, but by default they should resemble the same scope.
You need a custom scope for your VaadinUI implementation since you can have multiple VaadinUI instances ( multiple tabs or windows ) for the same session and application (depending on your application design).
In cdi-utils addon Tomi uses @VaadinScoped( VaadinScope.WINDOW) to tie the component to the current request via @RequestScoped , you will probably need the same approach for VaadinUI since VaadinUI is more synonymous with Window in vaadin 6.x from my understanding.
The UI's should be annotated with @VaadinUI which is a scope in itself, and if you only have one UI in it, then annotate that want also with @Root.
Clarification. In Vaadin 6 anyways when an Application closes Vaadin does not invalidate the Session. I think they added a policy in Vaadin 7 to close the session (since feature request was closed: http://dev.vaadin.com/ticket/6093) but I haven't verified it.
In Vaadin 6 the same session is used if a new Application is created in the same window so you need to be careful about what is bound to the session scope.
Building snapshot ... fails with selenium
Hi
I cloned the project from github and start "mvn clean install". Selenium tests are integrated, firefox starts and the build fails. Is there a way to skip selenium for local builds? Is there an official release?
Jan
The official release is coming a little later (currently plan is beta in March, final in April) - there will be some changes, most likely including a better UI scope that allows injecting components into injected components etc.
You should be able to skip tests the usual way - if I remember correctly:
-DskipTests
to skip running unit tests or
-Dmaven.test.skip=true
to also skip compiling them,
-DskipITs
to skip integration tests. There are similar properties (with somewhat different names) to the failsafe plug-in if you want to configure these in your POM.
Just in case anyone is still struggling with Guice and Vaadin, David Sowerby and myself have created an addon which hopefully should make it easier.
https://vaadin.com/directory#addon/v-guice
CDI with Java EE 7 always throws NPE. can you please provide us a full working solution or a video on how we can configure that.
Aimable RUHUMURIZA: CDI with Java EE 7 always throws NPE. can you please provide us a full working solution or a video on how we can configure that.
Don't know where you're doing your injections and having the NPE, but I'm using Vaadin 7.4 alpha with Java EE 7 and CDI is working just fine. You might want to elaborate. Also you can simply use Adam Bien's POM in this simple layout and build on it. It works just fine https://github.com/AdamBien/vaadin-with-javaee-pom/
Just clone and use as template for Vaadin 7 with Java EE 7 as backend
Seeraj Muneer:
Aimable RUHUMURIZA: CDI with Java EE 7 always throws NPE. can you please provide us a full working solution or a video on how we can configure that.
Don't know where you're doing your injections and having the NPE, but I'm using Vaadin 7.4 alpha with Java EE 7 and CDI is working just fine. You might want to
Seeraj Muneer:
Aimable RUHUMURIZA: CDI with Java EE 7 always throws NPE. can you please provide us a full working solution or a video on how we can configure that.
Don't know where you're doing your injections and having the NPE, but I'm using Vaadin 7.4 alpha with Java EE 7 and CDI is working just fine. You might want to elaborate. Also you can simply use Adam Bien's POM in this simple layout and build on it. It works just fine https://github.com/AdamBien/vaadin-with-javaee-pom/
Just clone and use as template for Vaadin 7 with Java EE 7 as backend
I'm doing the injection of the EJB in the MyVaadin class which extends UI and i have also added the CDI adds-on. I don't know what i 'm doing wrong here. If possible can you explain me in simple steps what you did in configuration in order to achieve that. I'm using NetBeans 8 and Vaadin plugin. If possible show some configuration steps you took to succed.
I want to do the configuration myself even if the AdamBien template my work. We're starting a new project and we used to be familiar with JSF but right now we want to migrate but keep the stack of Java EE 7. So please if you can explain what you did it would be better.
Install the Vaadin NetBeans plugin. Setup a new Vaadin project. Remove any serlet dependency in the POM.xml and replace it with a Java EE7 dependency. Install the Vaadin CDI addon. Create a beans.xml file. That should work.
What sort of customization do you want to do? What application server are you using?
I forgot to add, you don't need to do anything. No xml configs or any such thing. The beans.xml file will actually be an empty file.
I'm using WildFly 8 for Java EE7 . EclipseLin for JPA and EBJ for managing the transaction on the DB
OK great. I'm using the same stack. Like I said earlier, just setup a Vaadin project, add Java EE7 in the POM as a dependency and it should work. Make sure there's a beans.xml file as well
In the dependy i removed the servlet dependency as you said then i added javaee-api dependency. but what is the locattion of you beans.xml file because. I already have but i don't know if it is in the same location as yours
Here is my class where i do injection but nothing seems to work
@Theme("mytheme")
@SuppressWarnings("serial")
@CDIUI
@SessionScoped
public class MyVaadinUI extends UI implements Button.ClickListener,ItemClickEvent.ItemClickListener, FieldEvents.TextChangeListener {
private final HorizontalSplitPanel mainLayout = new HorizontalSplitPanel();
private final VerticalLayout leftLayout = new VerticalLayout();
private final FormLayout formEditor = new FormLayout();
private final TextField searchField = new TextField();
BeanItem<Customer> item;
private Table tableCustomer;
List<Customer> customerList = new ArrayList<Customer>();
BeanItemContainer<Customer> beanItemContainer;
FieldGroup groupFields = new FieldGroup();
Button save = new Button("Save");
@Inject
CustomerFacade customerEJB;
@Override
public void buttonClick(Button.ClickEvent event) {
try {
groupFields.commit();
Notification.show(""+customerEJB.findAll().size());
} catch (Exception e) {
e.printStackTrace();
}
}
@WebServlet(value = "/*", asyncSupported = true, initParams = {
@WebInitParam(name = "UIProvider", value = "com.vaadin.cdi.CDIUIProvider")
})
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "com.dev.vaadinapp.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
initLayout();
}
public void initLayout() {
initList();
initEditor();
mainLayout.addComponent(leftLayout);
mainLayout.addComponent(formEditor);
setContent(mainLayout);
searchField.addTextChangeListener(this);
}
public void initList() {
customerList = lookUp().findAll();
beanItemContainer = new BeanItemContainer(Customer.class, customerList);
tableCustomer = new Table("Table Customers");
tableCustomer.setContainerDataSource(beanItemContainer);
tableCustomer.setVisibleColumns((Object[]) new String[]{"name", "phone", "state", "city","fax"});
tableCustomer.addItemClickListener(this);
tableCustomer.setSelectable(true);
tableCustomer.setImmediate(true);
leftLayout.addComponent(tableCustomer);
leftLayout.setSizeFull();
leftLayout.setExpandRatio(tableCustomer, 1);
tableCustomer.setSizeFull();
searchField.setInputPrompt("Search");
leftLayout.addComponent(searchField);
leftLayout.setExpandRatio(searchField, 1);
leftLayout.setSpacing(true);
leftLayout.setMargin(true);
}
public void initEditor() {
Object[] colNames = (Object[]) tableCustomer.getVisibleColumns();
for (Object fieldName : colNames) {
TextField field = new TextField(fieldName.toString().toUpperCase());
field.setWidth("70%");
formEditor.addComponent(field);
groupFields.bind(field, fieldName);
}
formEditor.addComponent(save);
save.addClickListener(this);
formEditor.setMargin(true);
formEditor.setVisible(false);
}
@Override
public void itemClick(ItemClickEvent event) {
item = (BeanItem<Customer>) event.getItem();
groupFields.setItemDataSource(item);
formEditor.setVisible(true);
}
@Override
public void textChange(FieldEvents.TextChangeEvent event) {
//To change body of generated methods, choose Tools | Templates.
beanItemContainer.removeAllContainerFilters();
}
public CustomerFacade lookUp() {
try {
InitialContext context = new InitialContext();
return (CustomerFacade) context.lookup("java:global/VaadinApp/CustomerFacade");
} catch (NamingException ex) {
Logger.getLogger(MyVaadinUI.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
Aimable RUHUMURIZA: Here is my class where i do injection but nothing seems to work
@Theme("mytheme")
@SuppressWarnings("serial")
@CDIUI
@SessionScoped
public class MyVaadinUI extends UI implements Button.ClickListener,ItemClickEvent.ItemClickListener, FieldEvents.TextChangeListener {private final HorizontalSplitPanel mainLayout = new HorizontalSplitPanel();
private final VerticalLayout leftLayout = new VerticalLayout();
private final FormLayout formEditor = new FormLayout();
private final TextField searchField = new TextField();
BeanItem<Customer> item;
private Table tableCustomer;
List<Customer> customerList = new ArrayList<Customer>();
BeanItemContainer<Customer> beanItemContainer;
FieldGroup groupFields = new FieldGroup();
Button save = new Button("Save");
@Inject
CustomerFacade customerEJB;@Override
public void buttonClick(Button.ClickEvent event) {
try {
groupFields.commit();
Notification.show(""+customerEJB.findAll().size());
} catch (Exception e) {
e.printStackTrace();
}
}@WebServlet(value = "/*", asyncSupported = true, initParams = {
@WebInitParam(name = "UIProvider", value = "com.vaadin.cdi.CDIUIProvider")
})
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "com.dev.vaadinapp.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}@Override
protected void init(VaadinRequest request) {
initLayout();
}public void initLayout() {
initList();
initEditor();
mainLayout.addComponent(leftLayout);
mainLayout.addComponent(formEditor);
setContent(mainLayout);
searchField.addTextChangeListener(this);}
public void initList() {
customerList = lookUp().findAll();beanItemContainer = new BeanItemContainer(Customer.class, customerList);
tableCustomer = new Table("Table Customers");
tableCustomer.setContainerDataSource(beanItemContainer);
tableCustomer.setVisibleColumns((Object) new String{"name", "phone", "state", "city","fax"});
tableCustomer.addItemClickListener(this);
tableCustomer.setSelectable(true);
tableCustomer.setImmediate(true);
leftLayout.addComponent(tableCustomer);leftLayout.setSizeFull();
leftLayout.setExpandRatio(tableCustomer, 1);tableCustomer.setSizeFull();
searchField.setInputPrompt("Search");
leftLayout.addComponent(searchField);leftLayout.setExpandRatio(searchField, 1);
leftLayout.setSpacing(true);
leftLayout.setMargin(true);}
public void initEditor() {
Object colNames = (Object) tableCustomer.getVisibleColumns();
for (Object fieldName : colNames) {
TextField field = new TextField(fieldName.toString().toUpperCase());
field.setWidth("70%");
formEditor.addComponent(field);
groupFields.bind(field, fieldName);
}
formEditor.addComponent(save);
save.addClickListener(this);
formEditor.setMargin(true);
formEditor.setVisible(false);
}@Override
public void itemClick(ItemClickEvent event) {
item = (BeanItem<Customer>) event.getItem();
groupFields.setItemDataSource(item);
formEditor.setVisible(true);}
@Override
public void textChange(FieldEvents.TextChangeEvent event) {
//To change body of generated methods, choose Tools | Templates.
beanItemContainer.removeAllContainerFilters();
}public CustomerFacade lookUp() {
try {
InitialContext context = new InitialContext();
return (CustomerFacade) context.lookup("java:global/VaadinApp/CustomerFacade");
} catch (NamingException ex) {
Logger.getLogger(MyVaadinUI.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}}
" @WebServlet(value = "/*", asyncSupported = true, initParams = {
@WebInitParam(name = "UIProvider", value = "com.vaadin.cdi.CDIUIProvider")
})
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "com.dev.vaadinapp.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}"
You don't need that line, at least in my project it worked fine without any reference to any servlet. Comment out those lines. Also @CDIUI alone doesn't work in alpha3 of the addon. It should be @CDIUI("fooPath") or @CDUUI('") for /*
The injection is done in this class but when i call the
public void buttonClick(Button.ClickEvent event) {
try {
groupFields.commit();
Notification.show(""+customerEJB.findAll().size());
} catch (Exception e) {
e.printStackTrace();
}
When i call this method by clicking on the button that's where the error occurs
First off, you've too much code in the UI class. I tend to separate the layout and its logic to another class or classes and only use the UI class for displaying, ie setContent(myDisplayClassWithItsLogic).
There's nothing specific in terms of customization in the code above. Like I posted earlier, you'll save yourself a lot of time by using the github repo posted earlier as a base to build your app. Clone and look at its POM and do the same thing in yours.
yeah i know that this is too much code. As i said it is just a sample project as startup to demonstrate the features of Vaadin to my collegues and see if we can achieve the same thing we used to with JSF. I is going to be changed.
Thanks Seeraj.
I finally found the issues. First of all the i needed to remove the javax.servlet which is put in pom.xml when using the Vaadin NetBeans. that was the major issue that needed to be resolved and then i added Java EE api dependency which is javaee-api dependency which is in this case 7 cause i'm using Java EE 7 then finally add vaadin cdi dependency.
The codes in my class are not modified and i left them as there were since and i didn't comment the following codes because when i do it, the server is not recognizing the MyVaadinUI$Servlet so i lkeep this uncommented :
@WebServlet(value = "/*", asyncSupported = true, initParams = {
@WebInitParam(name = "UIProvider", value = "com.vaadin.cdi.CDIUIProvider")
})
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class, widgetset = "com.dev.manager.AppWidgetSet")
public static class Servlet extends VaadinServlet {
}
thanks a lot and i got it finally
Hi,
We should definitely have archetypes for Java EE environment so that people can start without hazzles. With Java EE and Vaadin CDI you don't actually need that servlet declaration nor web.xml at all. Vaadin CDI inspects whats available when web app starts and if no servlet is found it introduces Vaadin CDI capable servlet automatically.
Check out this example if you want extremely simple Java EE-Vaadin setup (supporting CDI):
https://github.com/mstahv/vaadin-java-ee-essentials-example
Note, that that don't support custom theme and client side extensions by default so not a universal solution...
cheers,
matti
Hi Matti Tahvonen, first of all thanks for the video about vaadin with Java EE 7. It really helped us to decide to use vaadin. But i have some couple questions. I would like to have an app which load the LoginView when start and then when the user successfully logged in to be directed to the mainView. The problem here i read the we can only have one navigator per UI and i want to have only one UI. in the mainView i will have menuLayout and contentLayout. I want to be able to have the remaining views rendered in the contentLayout every time i click on the menu located int menuLayout.
Can you please assit me
Hi,
Take a look at this example app we have been working with my smart collegue Peter Lehto.
https://github.com/peterl1084/cdiexample
cheers,
matti
Hi!
I have recently build a small app to be run under vaadin 7 along with its CDI add-on (vaadin-cdi 1.0.0.Beta2). It seems to work untill... I tried to touch a session scoped bean with @Resource-styled injection to one of its fields from within a button click listener. It seems that JBossAS7's weld cdi implementation gets confused when session scoped bean proxies try to get the underlying ejb context from the threads running out of servlet context (which is an issue when handling the asynchronous button click events).
Has anyone faced this problem? Any solution or workaround suggested, pls?
Regards