Show TOC

Injecting EJB Resources into Web ApplicationsLocate this document in the navigation structure

Use

In Java EE 5, you can use the simple mechanism of EJB resource injection which allows you to use EJB components by adding an annotation. In previous releases of the Java EE specification, the mechanism of accessing EJB resources required you to retrieve the enterprise beans using JNDI lookup.

Procedure

Use the @EJB annotation before declaring the variable or field representing the remote or local bean interface.

You can use the @EJB annotation without attributes or, optionally, use one or more of the following:

Attribute

Description

beanName

Specifies the EJB name. This attribute can be used only if the EJB is part of the same application or standalone module as the calling Web application.

beanInterface

Holds the Java class name of the required bean interface.

mappedName

The product-specific name to which this EJB is bound.

name

The logical name of the EJB reference within the declaring component's environment.

Example

The following example gets the local and remote interface of an enterprise bean, and uses them in the doGet method. The example illustrates using the @EJB annotation with or without attributes.

Sample Code
               public class EJB_servlet extends HttpServlet {

        //using the annotation without attributes
        @EJB
        private HelloEJBLocal helloEJBLoc;
                
   //using the annotation with attributes
        @EJB(beanName="HelloEJBBean",
        beanInterface=HelloEJBRemote.class
        description="Test Bean"
        )
        private HelloEJBRemote helloEJBRem;

        public void doGet( HttpServletRequest req , HttpServletResponse resp){ 

        //....  

              helloEJBLocal.sayHello(); //using the local interface
              
              helloEJBRem.sayHello(); //using the remote interface

              //....    
        }