managed bean EJB injection

南笙酒味 提交于 2020-01-15 18:51:57

问题


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;
  }
}

回答1:


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.



来源:https://stackoverflow.com/questions/5903356/managed-bean-ejb-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!