Search code examples
javaejbvaadin7inject

@EJB and @Inject does not work for my vaadin class


i try to inject my singleton startup bean, which initializes the CustomerDataModel, into a vaadin class.

@Startup
@Singleton
public class StartupBean {
   @Resource(lookup = "java:global/customerDatabase")
   private String customerDatabasePath;

   @Resource(lookup = "java:global/addressDatabase")
   private String addressDatabasePath;

   private CustomerDataModel dataModel = null;

   public StartupBean() {

   }

   @PostConstruct
   private void startup() {
       File customerDatabase = new File(customerDatabasePath);
       File addressDatabase = new File(addressDatabasePath);

       dataModel = new DataModelImpl(customerDatabase, addressDatabase);
   }

   @PreDestroy
   private void shutdown() {

   }

   public CustomerDataModel getDataModel() {
       return dataModel;
   }
}

Here is my vaadin class which needs a fully initialized startup bean

@DependsOn("StartupBean")
@Stateless
public class Workspace extends UI {
   @EJB
   private StartupBean startupBean;

   @WebServlet(value = "/*", asyncSupported = true)
   @VaadinServletConfiguration(productionMode = false, ui = Workspace.class)
   public static class Servlet extends VaadinServlet {
   }

   @Override
   protected void init(VaadinRequest request) {
   if(startupBean == null) {
      System.out.println("error");
   }

I tried it with @EJB and @Inject, neither works. I always get a nullpointer at startupBean. I also have a bean.xml at WEB-INF

i tried it according to http://java.dzone.com/articles/cdi-di-p1 and http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

Does anyone know what i am doing wrong?


Solution

  • The problem is that your Workspace object (extends Vaadin UI) cannot be a stateless EJB. One instance of those is used by one single user. Instead your should start using Vaadin CDI and annotate it with @CDIUI. Then you can inject the EJB to your CDI managed (~ session scoped) Vaadin UI.