Search code examples
jsfejbmanaged-beanconverters

managed bean EJB injection


i'm having many managed beans and was wondering if i could create a UtilClass where i put my services calls (@EJB). I've already tried it but i'm having a NullPointerException. this is how my UtilClass and my managed bean look like:

public class UtilClass{
@EJB
private static MyFirstEjbLocal myFirstService;
@EJB
private static  MySecondEjbLocal mySecondService;
//other services
//getters

 }


public class MyManagedBean{
   public String myMethod(){

   UtilClass.getMyFirstService.doSomethingInDB();

   return null;
  }
}

Solution

  • I would suggest you to do the following, since apparently you are having a lot of services and want to have them grouped together, you can create an "abstract" bean and make your managed bean extend such "abstract" bean, in this way you can access the EJB's in a structural and safe way, the following code will explain what I mean:

    public class MyAbstractBean{
      @EJB
      protected MyFirstEjbLocal myFirstService;
      @EJB
      protected  MySecondEjbLocal mySecondService;
      // All your other EJB's here
      ...
      // All other variables and methods you could need
    }
    
    
    public class MyManagedBean
       extends MyAbstractBean{
    
        public String myMethod1(){
    
          myFirstService.doSomethingInDB();
          return "";
    
        }
    
        public String myMethod2(){
    
          mySecondService.doSomethingInDB();
          return "";
    
        }
    }
    

    Please refer to JavaEE5 EJB FAQ if you need to clarify more concepts on the matter.