6 Replies Latest reply on Sep 21, 2012 6:34 AM by nickarls

    StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature

    schanamolu

      Hi,

       

      The templates are not the issue as templates are working fine. I have added beanx.xml now, constructor is getting invoked.

       

      StatesLess EJB is not Injected and the value is null. Iam trying to deploy everything in one war file. Let me know if Iam missing any thing.

       

      iam getting null pointer exception beacuse StatlessLess EJB is null.

       

       

       

      ===================================================

       

      Caused by: java.lang.NullPointerException
      at com.ibytecode.businesslogic.controller.ActiorController.<init>(ActiorController.java:69) [classes:]
      at com.ibytecode.businesslogic.controller.ActiorController$Proxy$_$$_WeldClientProxy.<init>(ActiorController$Proxy$_$$_WeldClientProxy.java) [classes:]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.6.0_13]
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) [rt.jar:1.6.0_13]
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) [rt.jar:1.6.0_13]
      at java.lang.reflect.Constructor.newInstance(Constructor.java:513) [rt.jar:1.6.0_13]
      at java.lang.Class.newInstance0(Class.java:355) [rt.jar:1.6.0_13]
      at java.lang.Class.newInstance(Class.java:308) [rt.jar:1.6.0_13]
      at org.jboss.weld.util.reflection.SecureReflections$16.work(SecureReflections.java:343) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
      at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
      at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInstantiation(SecureReflectionAccess.java:173) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]

       

      ========================================================================================================================

       

      Pl check the following of sourcecode xhtml, Controller and StatelessEJB. Pl also check Attached sourceCode.

       

      Controller:

       

      package com.ibytecode.businesslogic.controller;

      import java.io.Serializable;

      import javax.ejb.EJB;
      import javax.enterprise.context.SessionScoped;
      import javax.inject.Named;

      import com.ibytecode.businesslogic.ActorBean;
      import com.ibytecode.entity.Actor;

      @Named(value = "actorService")
      @SessionScoped
      public class ActorController implements Serializable {

      /**
      * Injected GreeterEJB client
      */
      @EJB
      private ActorBean actorEJB;

      private String greeting;

      public String getGreeting() {

      return greeting;
      }

      public ActorController() {

      Actor actor = new Actor();
      actor.setActorId(new Short("201"));
      actor = actorEJB.findActor(actor);

      if (actor != null) {
      greeting = "Hello, " + actor.getFirstName() + " "
      + actor.getLastName() + "!";
      } else {
      greeting = "No such user exists! Use 'emuster' or 'jdoe'";
      }
      }
      }

       

      =============================================

      XHTML

       

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:f="http://java.sun.com/jsf/core"
      >

       

      <h:body>
      <ui:composition template="template/common/template.xhtml">
      <ui:define name="content">
      <h:messages />
      <h:outputText value="#{actorService.greeting}"/>
      </ui:define>
      </ui:composition>
      </h:body>
      </html>

       

       

       

      =========================================================

       

       

       

      package com.ibytecode.businesslogic;

      import java.util.List;

      import javax.ejb.Stateless;
      import javax.persistence.EntityManager;
      import javax.persistence.PersistenceContext;
      import javax.persistence.Query;

      import com.ibytecode.entity.Actor;

      @Stateless
      public class ActorBean {

      public ActorBean() { }

      @PersistenceContext(unitName = "FirstEJBsProject")
      private EntityManager entityManager;

      private String greeting;

      public String getGreeting() {
      return greeting;
      }

      public void setGreeting(String greeting) {
      this.greeting = greeting;
      }

      public void saveActor(Actor actor) {

      entityManager.persist(actor);

      }

      public Actor findActor(Actor actor) {

      Actor p = entityManager.find(Actor.class, actor.getActorId());

      return p;

      }

      public List<Actor> retrieveAllActors() {

      String q = "SELECT p from " + Actor.class.getName() + " p";

      Query query = entityManager.createQuery(q);

      List<Actor> actors = query.getResultList();

      return actors;

      }

      }

       

      Early response would be appreciated.

       

      Thanks,

      Sree

        • 1. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
          lafr

          Move your code out of the constructor into another method annotated with @PostConstruct.

          Injection is not yet done, when the bean is instantiated. You have to do it later, immediatly after instantiation.

          • 2. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
            schanamolu

            Frank,

             

            Thanks a lot. That helped in resolve. I try to play with both @EJB and @Inject on stateless, They both seems to behave same way. When can we use @EJB and when can we use @Inject on stateless EJB in CDI Enviornment J2EE Container.

             

            Thanks,

            Sree

            • 3. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
              lafr

              Just two comments:

              As your problem is solved, you should mark your question as answered (or how this is called in English here) and mark my answer as helpful or right.

              And please open a new discussion for a new question.

               

              As far as I found out that there is no general rule to favor EJB over Inject or the other way around.

              I read somewhere and advise to go with Inject as the future direction.

               

              The application I'm maintaining consists of 2 projects and deployment units.

              A war-file with the web-application / UI and a ear-file containing webservices for access (Webservice), the business logic (Session Beans) and the database access layer (Entity Beans).

              For the web-app I'm using JSF with CDI/Inject and in the ear-app EJB as I think it's best to avoid mixing it.

              • 4. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
                nickarls

                Frank Langelage wrote:

                 

                Move your code out of the constructor into another method annotated with @PostConstruct.

                Injection is not yet done, when the bean is instantiated. You have to do it later, immediatly after instantiation.

                 

                Not so sure about that. The spec, section 5.5.2 sayeth

                 

                 

                Any @PostConstruct callback declared by a class X in the type hierarchy of the bean is called after all initializer methods declared by X or by superclasses of X have been called, after all injected fields declared by X or by superclasses of

                X have been initialized, and after all Java EE component environment resource dependencies declared by X or by superclasses of X have been injected

                Frank Langelage wrote:

                 

                • 5. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
                  lafr

                  That's what I wrote in my eyes or at least tried to express.

                   

                  In the original version the injected object actorEJB was used in the constructor:

                  @SessionScoped

                  public class ActorController implements Serializable {

                       @EJB private ActorBean actorEJB;

                   

                       public ActorController() {

                            Actor actor = new Actor();
                            actor.setActorId(new Short("201"));
                            actor = actorEJB.findActor(actor);

                       }

                  }

                  That's too early, because the injection is not yet done at this point in time. Injection comes after intialization.

                   

                  @SessionScoped

                  public class ActorController implements Serializable {

                       @EJB private ActorBean actorEJB;

                   

                       public ActorController() {

                       }

                   

                      @PostConstruct

                      public void init() {

                            Actor actor = new Actor();
                            actor.setActorId(new Short("201"));
                            actor = actorEJB.findActor(actor);

                       }

                  }

                  This wiill work, because when the PostConstruct annotated method is called by the container, all initialization and injections are done. The created instance of the class is ready and fully usable.

                  • 6. Re: StatesLess EJB is not Injected from controller and the value is null using J2EE 6 CDI Feature
                    nickarls

                    Oops, I misread your post, I just noticed @PostConstruct and "Injection not done" and connected them into one sentence ;-)