@Stateless(name="personBean") @Local(PersonManager.class) public class PersonManagerBean implements PersonManager { @PersistenceContext(unitName="unit") private EntityManager em; @Override public void save(Person person) { em.persist(person); } }
Way 1: Dependency Injection
@Stateless(name="dependencyInjectionService") @Local(Ejb3Service.class) public class Ejb3ServiceDependencyInjectionBean implements Ejb3Service { @EJB(beanName="personBean") private PersonManager personManager; @Override public void savePerson(Person person) { personManager.save(person); } }
beanName attribute (personBean) of @EJB annotation matches the name attribute of @Stateless annotation.
Way 2: Initial Context Look Up
@Stateless(name="initalContextService") @Local(Ejb3Service.class) @EJB(name="ejb/personManager", beanInterface=PersonManager.class, beanName="personBean") public class Ejb3ServiceInitialContextBean implements Ejb3Service { @Override public void savePerson(Person person) { PersonManager personManager = null; try { Context ctx = new InitialContext(); personManager = (PersonManager) ctx.lookup("java:comp/env/ejb/personManager"); } catch (javax.naming.NamingException ne) { throw new EJBException(ne); } personManager.save(person); } }
@EJB annotation at class level registers the EJB with the beanName (i.e. personBean) in the JNDI ENC. The name attribute specifies the logical name (i.e. ejb/personManager) of the EJB in the JNDI ENC. This logical name can be looked up by InitialContext. (prefixed with “java:comp/env”)
Way 3: EJB Context Look up
@Stateless(name="ejbContextService") @Local(Ejb3Service.class) @EJB(name="ejb/personManager", beanInterface=PersonManager.class, beanName="personBean") public class Ejb3ServiceEjbContextBean implements Ejb3Service { @Resource private EJBContext ejbContext; @Override public void savePerson(Person person) { PersonManager personManager = (PersonManager) ejbContext.lookup("ejb/personManager"); personManager.save(person); } }
With Ejb context lookup, the lookup string doesn’t need to be prefixed with “java:comp/env”
Now write a servlet to test
public class PersonServlet extends HttpServlet { @EJB(beanName="ejbContextService") private Ejb3Service service1; @EJB(beanName="initalContextService") private Ejb3Service service2; @EJB(beanName="dependencyInjectionService") private Ejb3Service service3; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { service1.savePerson(new Person("Sun8")); service2.savePerson(new Person("Sun9")); service3.savePerson(new Person("Sun10")); } }