SlideShare a Scribd company logo
1 of 6
Download to read offline
Subscribe Now for FREE! refcardz.com
                                                                                                                                                                  tech facts at your fingertips

                                              CONTENTS INCLUDE:
                                                   What is EJB3?



                                                                                          Dependency Injection in EJB 3
                                              n	



                                              n	
                                                   Resource Injection
                                              n	
                                                   Injection of EJB References
                                              n	
                                                   Injecting JPA Resources
                                              n	
                                                   Injecting Spring Beans in EJB 3
                                              n	
                                                   Hot Tips and more...
                                                                                                                                                                                      By Debu Panda


                                                      WHAT IS EJB 3?                                                                 DEPENDENCY INJECTION IN EJB 3

                                                    Enterprise JavaBeans (EJB) is a platform for building portable,                 With EJB 3, dependency injection has greatly simplified accessing
                                                    reusable, and scalable business applications using the Java                     both EJB resources—such as JDBC DataSource, JMS Objects,
                                                    programming language. Since its initial incarnation, EJB has                    and JPA Entity Manager—and services—such as Timer, User
                                                    been touted as a component model or framework that lets you                     Transaction, and Web Services. You will find this Refcard useful
                                                                                                                                    when building enterprise Java applications with EJB 3 and JPA.
                                                    build enterprise Java applications without having to reinvent
                                                                                                                                    It lists all metadata annotations, describes them and provides
                                                    services such as transactions, security, and automated persistence
                                                                                                                                    examples. It also provides descriptions for XML elements that
                                                    for building an application.                                                    you can use for injection.
                                                    EJB 3 greatly simplifies development by adopting a POJO                         Most enterprise Java applications use external resources
                                                    programming model. As shown in the following figure an                          and services such as Data Source, EJB, or web services. EJB 3
                                                    annotation transforms a simple POJO to an EJB.                                  makes using resources and services simpler by implementing
                                                                                                                                    dependency injection.
                                                                                                                                    Dependency injection allows you to simply declare component

                                                                 J        + @ =                                                     dependencies and let the EJB container deal with the complexities
       www.dzone.com




                                                                                                                                    of instantiating, initializing, and sequencing resources and
                                                                                                                                    supplying service or resource references to clients as required.
                                                               POJO               Annotation               EJB                      Development frameworks like Spring framework originally
                                                                                                                                    popularized dependency injection.
                                                    EJB 3 not only simplifies development of session and message                    In EJB 3, you may think of dependency injection as the inverse of
                                                    driven beans but it also radically simplifies the persistence                   JNDI. It is the responsibility of the container to inject an object
                                                    model by implementing a simplified Object-Relational Mapping                    based on the dependency declaration. The figure below com-
                                                    approach similar to Oracle TopLink and JBoss Hibernate as a                     pares dependency injection with JNDI.
                                                    part of the Java Persistence API. Note that JPA replaces EJB
                                                    2 CMP Entity beans in the EJB 3 spec, while being available
                                                    outside of the Java EE container.                                                                                              Resources
                                                                                                                                                                                                   Lookup
                                                    Following is an example of a simple EJB 3 Stateless session bean.                   EJB             JNDI lookup

                                                    import javax.ejb.Stateless;                                                                                                     Beans
                                                    import ejb3inaction.example.persistence.Bid;
Dependency Injection in EJB 3




                                                    @Stateless
                                                    public class PlaceBidBean implements PlaceBid {
                                                                                                                                      Resources                                                   Dependency
                                                       ...
                                                                                                                                                                                                   injection
                                                                                                                                                     Container         Injection            EJB
                                                       public PlaceBidBean() {}
                                                                                                                                       Beans
                                                          public Bid addBid(Bid bid) {
                                                          System.out.println(“Adding bid, bidder ID=”

                                                                        + bid.getBidderID()
                                                                                                                                                                 Get More Refcardz
                                                                        + “, item ID=” + bid.getItemID()                                                                    (They’re free!)
                                                                        + “, bid amount=”
                                                                 + bid.getBidAmount() + “.”);
                                                                                                                                                                 n    Authoritative content
                                                              return save(bid);
                                                                                                                                                                 n    Designed for developers
                                                    }                                                                                                            n    Written by top experts
                                                    ...                                                                                                          n    Latest tools & technologies
                                                    }                                                                                                            n    Hot tips & examples
                                                    import javax.ejb.Local;
                                                                                                                                                                 n    Bonus content online
                                                    import ejb3inaction.example.persistence.Bid;
                                                                                                                                                                 n    New issue every 1-2 weeks
                                                    @Local public interface PlaceBid {                                                            Subscribe Now for FREE!
                                                           Bid addBid(Bid bid);
                                                                                                                                                       Refcardz.com
                                                    }



                                                                                                                 DZone, Inc.   |   www.dzone.com
2
                                                                                                                                  Dependency Injection in EJB 3
  tech facts at your fingertips




                                                                                      The following annotations can be used in a field or a setter method
DEPENDENCY INJECTION IN EJB 3                                  continued              for dependency injection. However, these annotations may also
                                                                                      be applied at the class level for defining dependencies and then
                                                                                      used with JNDI look up.
                  Note that annotations and descriptors are not
   Hot            mutually exclusive. In fact, you can use both
                                                                                       Annotations                       Usage                        Components that
   Tip                                                                                                                                                can use
                  together. Deployment descriptor entries override                     javax.annotation.Resource         Dependency injection         EJB, Web,
                  configuration values specified using metadata                                                          of resources such as         Application Client
                                                                                                                         DataSource, and JMS
                  annotations.                                                                                           objects

                                                                                       javax.ejb.EJB                     Dependency injection         EJB, Web,
                                                                                                                         of Session beans             Application Client
You can use either metadata annotations or XML descriptors
                                                                                       javax.xml.ws.WebServiceRef        Dependency injection         EJB, Web,
to use dependency injection.                                                                                             of Web services              Application Client

Refer to the following Java EE 5 specifications and XML schema                         javax.persistence.                Dependency injection         EJB, Web
                                                                                       PersistenceContext                of container-managed
for more information on dependency injection.
                                                                                                                         EntityManager
JSR 220                                                                                javax.persistence.                Dependency injection         EJB, Web
Enterprise JavaBeans 3.0:                                                              PersistenceUnit                   of EntityManagerFactory
http://www.jcp.org/en/jsr/detail?id=220
JSR 224                                                                                RESOURCE INJECTION
Java API for XML-Based Web Services (JAX-WS) 2.0:
http://jcp.org/en/jsr/detail?id=224                                                   javax.annotation.Resource
                                                                                      The @Resource annotation is used to inject any of the following:
JSR 250:
                                                                                      JDBC data sources, JMS connection factories, JMS destinations,
Common Annotations for the Java Platform:
                                                                                      mail resource, environment entries, timer service, UserTransaction,
http://www.jcp.org/en/jsr/detail?id=250
                                                                                      and EJBContext.
Schema for EJB 3 deployment descriptor:
                                                                                      The following table shows attributes for the @Resource annotation.
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
Schema that defines common schema components:                                          Parameter            Type             Description                      Default

http://java.sun.com/xml/ns/javaee/javaee_5.xsd                                         authentication       enum             The type of authentication       CONTAINER
                                                                                       Type                 Authentication   required for accessing the
Dependency injection is supported only on managed classes                                                   Type             resource. The CONTAINER
                                                                                                            {CONTAINER,      value means that the
and not on regular POJO.                                                                                    APPLICATION}     container’s security context
                                                                                                                             is used for the resource. The
                                                                                                                             APPLICATION value means
                   Dependency injection is supported only on                                                                 that authentication for the
    Hot            managed classes such as Session Beans or In-
                                                                                                                             resource must be provided
    Tip                                                                                                                      by the application.
                   terceptors and not on regular POJO. Hence you                       name                 String           The referred resources is        “”
                                                                                                                             bound under this name in
                   cannot use injection on helper classes.                                                                   the enviornment-naming
                                                                                                                             context as java:comp/
                                                                                                                             env/<Name>
The following table depicts what type of managed classes can
                                                                                       type                 Object           Type of the resource             Object.class
inject what objects.                                                                                                         being referenced. Example:
                                                                                                                             javax.sql.DataSource
Resources                         Stateless   Stateful   MDB     Interceptors
                                                                                       shareable            Boolean          Specifies whether the            True
JDBC DataSource                   Yes         Yes        Yes     Yes                                                         resource can be shared.

JMS Destinations,                 Yes         Yes        Yes     Yes                   description          String           The description of the           “”
Connection Factories                                                                                                         resource.

                                                                                       mappedName           String           A vendor-specific name           “”
Mail Resources                    Yes         Yes        Yes     Yes
                                                                                                                             that the resource may be
UserTransaction                   Yes         Yes        Yes     Yes                                                         mapped to, as opposed to
                                                                                                                             the JNDI name.
Environment Entries               Yes         Yes        Yes     Yes

EJBContext                        Yes         Yes        Yes     No                  You can inject a resource at the field or setter method level.
Timer Service                     Yes         No         Yes     No                  The following example shows data source injection at the field level:
                                                                                         @Resource(name=”jdbc/ActionBazaarDS”)
Web Service reference             Yes         Yes        Yes     Yes
                                                                                         private DataSource dataSource;
EnityManager,                     Yes         Yes        Yes     Yes
EntityManagerFactory                                                                 The following code shows data source injection at the setter
                                                                                     method level:
Java EE 5 introduced several metadata annotations as part of                             private DataSource dataSource;
JSR 250. Although primarily geared toward EJB, these annota-                             @Resource(name=”jdbc/ActionBazaarDB”)
                                                                                         public void setDataSource(DataSource dataSource) {
tions also apply to Java EE components such as Servlets, JSF
                                                                                         this.dataSource = dataSource;
managed beans, and application clients.                                                  }


                                                                   DZone, Inc.   |   www.dzone.com
3
                                                                                                                                        Dependency Injection in EJB 3
    tech facts at your fingertips




                                                                                               resource-env-ref
 RESOURCE INJECTION                               continued
                                                                                               The resource-env-ref is used to specify references to JMS
                                                                                               destination resources such as a Queue or Topic.

                                                                                                Element/Attribute Name    Description
                    Although setter injection might seem like a
     Hot                                                                                        resource-env-ref-name     The name used to bind the referenced JMS
     Tip            little more work, it provides a couple of distinct                                                    destination to the ENC. Same as the name
                                                                                                                          element in the @Resource annotation.
                    advantages. First, it is easier to unit-test by
                                                                                                mapped-name               A vendor-specific global JNDI name for the
                    invoking the public setter method from a testing                                                      referenced JMS destination.
                    framework like JUnit. Second, it is easier to put                           resource-env-type         Type of JMS destination referenced, such as javax.
                                                                                                                          jms.Queue or javax.jms.Topic.
                    initialization code in the setter if you need it.
                                                                                                injection-target          Target where the referenced destination is
                                                                                                                          injected when dependency injection is used.

EJB 3 allows you to explicitly specify a global JNDI name using
                                                                                               <resource-env-ref>
the mappedName parameter of the @Resource annotation. For                                      <resource-env-ref-name>jms/OrderBillingQueue</resource-env-ref-name>
example, if you’re using the Oracle Application Server and you                                 <resource-env-ref-type>
have a data source with a global JNDI name of jdbc/OracleDS,                                      javax.jms.Destination

you can specify the resource mapping as follows:                                               </resource-env-ref-type>
                                                                                               <injection-target>
   @Resource(name=”jdbc/ActionBazaarDS”, mappedName=”jdbc/                                        <injection-target-class>
   OracleDS”)                                                                                          ejb3inaction.example.buslogic.PlaceOrderBean
   private javax.jdbc.DataSource myDB;                                                            </injection-target-class>
                                                                                                      <injection-target-name>billingQueue</injection-target-name>
XML elements to define Resource Injection                                                      </injection-target>
                                                                                               </resource-env-ref>
If you are using deployment descriptor (ejb-jar.xml) instead of
annotations, then you must use resource-ref, resource-env-ref                                  env-entry
or env-entry XML elements to define dependencies.                                              The env-entry defines environment entries for an EJB.

resource-ref                                                                                    Element/Attribute Name    Description

The resource-ref is used to specify resource references.                                        env-entry-name            The name used in the environment entry in
Example: data source and JMS connection factories.                                                                        the ENC. Same as the name element in the
                                                                                                                          @Resource annotation.

 Element/Attribute Name             Description                                                 env-entry-type            Type of the env entry used. Legal types are
                                                                                                                          java.lang.Boolean, java.lang.Byte, java.lang.
 res-ref-name                       The name used to bind the referenced resource
                                                                                                                          Character, java.lang.String, java.lang.Short,
                                    into the ENC. Same as the name element in the
                                                                                                                          java.lang.Integer, java.lang.Long, java.lang.Float,
                                    @Resource annotation.
                                                                                                                          and java.lang.Double.
 mapped-name                        A vendor-specific global JNDI name for the
                                                                                                env-entry-value           Value specified for the environment entry.
                                    referenced resource.
                                                                                                injection-target          Target where the referenced destination is
 res-type                           Fully qualified class of the type of resource
                                                                                                                          injected when dependency injection is used.
                                    referenced. Example: javax.sql.DataSource.

 res-auth                           Authentication type for the resource. Valid values         The injection-target defines the name of a class and a name
                                    are Container or Application.                              (field or property) within that class into which a resource,
 res-sharing-scope                  Specifies whether multiple beans can share                 EJB, or entity manager should be injected as we saw in the
                                    the resource. Valid values are Shareable and               above examples.
                                    Unshareable

 injection-target                   Target where the referenced resource is injected            Element/Attribute Name    Description
                                    when dependency injection is used.
                                                                                                injection-target-class    The fully qualified name of the class into which a
                                                                                                                          resource, EJB, or entity manager should be injected.
<resource-ref>
                                                                                                injection-target-name     Name of the injection target, i.e., the name of the
 <res-ref-name>jdbc/ActionBazaarDS</res-ref-name>                                                                         property or field in the injection target class.
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 <res-sharing-scope>Shareable</res-sharing-scope>
                                                                                                 INJECTION OF SESSION EJB REFERENCES
 <injection-target>
                                                                                               Like resource injection, you can inject Session bean references
        <injection-target-class>
                                                                                               into another EJB or other managed class using annotations
      actionbazaar.buslogic.BidManagerBean</injection-target-class>
                                                                                               or deployment XML. If you prefer annotations you can use
        <injection-target-name>dataSource</injection-target-name>
                                                                                               @javax.ejb.EJB annotations to inject either remote or local
</injection-target>
                                                                                               EJB references. Using deployment XML, you can inject
</resource-ref>                                                                                remote EJB references with ejb-ref and local EJB references
                                                                                               with ejb-local-ref.


                                                                             DZone, Inc.   |   www.dzone.com
4
                                                                                                                                           Dependency Injection in EJB 3
   tech facts at your fingertips




@javax.ejb.EJB
Injects a session bean reference into a field or method.                                                                EJB 3 specification does not require
                                                                                                            Hot         injecting references of remote EJB into a
Parameter            Type          Description                                Default                       Tip
                                                                                                                        different instance of container. For example
name                 String        The name used to bind the                  “”
                                   referenced EJB to the ENC.
                                                                                                                        if you have an EJB with a remote interface
                                                                                                                        deployed into an instance of a container,
beanInterface        Class         The bean interface used to access          Object.
                                   the EJB                                    class                                     EJB 3 specification does not require inject-
mappedName           String        Type of the resource being referenced.     “”
                                                                                                                        ing instance of that EJB into another EJB
                                   Example: javax.sql.DataSource                                                        deployed in another container.
beanName             String        Specifies whether the resource can         “”
                                   be shared.

description          String                                                                        INJECTINg JPA RESOURCES

 @EJB(name=”BidManagerRemote”)                                                                   The JPA EntityManager is the bridge between the OO and
 private BidManager bidManager;                                                                  relational worlds as depicted in the following figure.


                       You must not inject a Stateful session bean
        Hot
                                                                                                                    Save                                  SQL

                       into a stateless object, such as a stateless                                Object
                                                                                                                                 EntityManager
        Tip
                                                                                                                                                                        Relational
                                                                                                                                                                        Database
                                                                                                                   Retrieve                              Results
                       session bean or servlet that may be
                       shared by multiple concurrent clients (you
                       should use JNDI in such cases instead).                                   JPA supports two types of EntityManager: container-managed
                       However, injecting an instance of a state-                                and application-managed. As the name suggests the lifecycle
                       less session bean into a stateful session                                 of the container manages container-managed EntityManager
                       bean is perfectly legal.                                                  whereas the lifecycle (creation, destruction) is performed by
                                                                                                 application. An application-managed EntityManager is created
                                                                                                 from an EntityManagerFactory.
ejb-local-ref
                                                                                                 Injecting container-managed EntityManager
Used to specify a dependency on the local interface of a
                                                                                                 You can inject a container-managed EntityManager (either
session bean.
                                                                                                 transaction scoped or extended) using @javax.persistence.
Element/Attribute Name              Description                                                  PersistenceContext annotation.
ejb-ref-name                        The name used to bind the referenced EJB to                  @javax.persistence.PersistenceContext
                                    the ENC. Same as the name element in the @EJB
                                    annotation. ejb-ref-name must be specified.                  The following table defines the parameters/attributes of this
                                                                                                 annotation.
ejb-link                            The name of the target enterprise bean. This
                                    optional setting is used to link an EJB reference to          Parameter       Type           Description                       Default
                                    a target enterprise bean.
                                                                                                  name            String         The name used to bind             “”
local                               The EJB 3 local business interface.                                                          the referenced persistence
                                                                                                                                 context to the ENC
ref-type                            The EJB reference type, i.e. “session”.
                                                                                                  unitName        String         Name of the persistence unit      “”
injection-target                    Target where the EJB reference is injected when                                              referenced
                                    dependency injection is used.
                                                                                                  type            Persistence    Type of persistence context,      TRANSACTION
                                                                                                                  ContextType    i.e., Transaction or Extended.
ejb-ref                                                                                                                          Extended is supported only in
                                                                                                                                 stateful session beans.
Used to specify a dependency on the remote interface of a
session bean.                                                                                     properties      Persistence    A name value-pair of vendor-      {}
                                                                                                                  Property[]     specific persistence properties
Element/Attribute Name              Description
                                                                                                 You can inject a transaction scoped EntityManager as follows:
ejb-ref-name                        The name used to bind the referenced EJB to
                                    the ENC. Same as the name element in the @EJB                    @PersistenceContext(unitName=”actionBazaar”)
                                    annotation. ejb-ref-name must be specified.                      private EntityManager entityManager;

ejb-link                            The name of the target enterprise bean. This                 An extended scoped EntityManager can only used in a stateful
                                    optional setting is used to link an EJB reference            session bean as in the following example:
                                    to a target enterprise bean.
                                                                                                     @Stateful
remote                              The EJB 3 remote business interface type.                        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
ref-type                            The EJB reference type, i.e. “session”.                          public class PlaceOrderBean implements PlaceOrder {
                                                                                                         @PersistenceContext(unitName = “actionBazaar”, type =
injection-target                    Target where the EJB reference is injected when
                                                                                                                        PersistenceContextType.EXTENDED)
                                    dependency injection is used.
                                                                                                     EntityManager em;



                                                                              DZone, Inc.   |   www.dzone.com
5
                                                                                                                                         Dependency Injection in EJB 3
    tech facts at your fingertips




Injecting JPA Resources, continued
                                                                                                   INJECTINg WEB SERvICE REFERENCES
The persistence-context-ref is similar to @PersistenceContext;
it defines references to a container-managed entity manager.                                         @javax.xml.ws.WebServiceRef

                                                                                                  Element                  Description
 Element/Attribute Name             Description
                                                                                                  name                     The JNDI name for the web service.
 persistence-context-ref-           The name used to bind the referenced persistence
 name                               context to the ENC. Same as the name element in               wsdlLocation             The WSDL location for the service. If not specified,
                                                                                                                           then it is derived from the referenced service class.
                                    the @PersistenceContext annotation.
                                                                                                  type                     The Java type of the resource.
 persistence-unit-name              Name of the persistence unit referenced.
                                                                                                  value                    The service class, always a type extending javax.xml.
 persistence-context-type           Type of persistence context, i.e., Transaction or                                      ws.Service.
                                    Extended. Extended is supported only in stateful
                                                                                                  mappedName               Vendor-specific global JNDI name for the service.
                                    session beans.

 persistence-property               A name value-pair of vendor-specific persistence             You can inject an endpoint interface as follows:
                                    properties.                                                     @WebServiceRef(TrackDeliveryService.class)
 injection-target                   Target where the EntityManager is injected when                 private TrackDeliverySEI deliveryService;
                                    dependency injection is used.
                                                                                                 You can inject a service interface as follows:
<persistence-context-ref>                                                                           @WebServiceRef
                                                                                                    private TrackingService service;
        <persistence-context-ref-name>
                             ActionBazaar                                                         service-ref
        </persistence-context-ref-name>                                                           The service-ref XML element is used to specify dependency on a
        <persistence-unit-name>actionBazaar</persistence-unit-name>                               web service if you are using deployment descriptor. The following
        <persistence-context-type>Transaction</persistence-context-type>                          table contains only the elements that are used from EJB clients.
        <injection-target>
             <injection-target-class>                                                             Element/Attribute Name   Description
            ejb3inaction.example.buslogic.PlaceBidBean                                            service-ref-name         The name used to bind the referenced web service
        </injection-target-class>                                                                                          into the ENC. Same as the name element in the @
                                                                                                                           WebServiceRef annotation.
             <injection-target-name>em</injection-target-name>
        </injection-target>                                                                       service-interface        Fully qualified class for the JAX-WS service interface
                                                                                                                           the client depends on., i.e. javax.xml.rpc.Service.
    </persistence-context-ref>
                                                                                                  service-ref-type         Type of service that will be returned.
Injecting EntityManagerFactory                                                                    wsdl-file                The URL location of the WSDL.

   @javax.persistence.PersistenceUnit                                                             handler-chains           Defines handler chain.

   @Stateless                                                                                     injection-target         Target where the web service reference is injected
                                                                                                                           when dependency injection is used.
   public class ItemManagerBean implements ItemManager {
   @PersistenceUnit                                                                               The detailed schema for the service-ref can be found online at
        private EntityManagerFactory entityManagerFactory;                                        java.sun.com/xml/ns/javaee/javaee_web_services_client_1_2.xsd.
   private EntityManager entityManager;
   @PostConstruct
        public void initialize() {                                                                 INJECTINg SPRINg BEANS IN EJB 3
            entityManager = entityManagerFactory.createEntityManager();
        }                                                                                         The Spring Framework is one of the driving forces behind popular-
   }                                                                                              izing the POJO programming model and dependency injection.
                                                                                                  In this section we will examine how you can inject and use Spring
 Parameter        Type               Description                       Default
                                                                                                  POJOs into EJB 3 Session beans or Message Driven Beans.
 name             String             The name used to bind             “”
                                     the referenced persistence
                                                                                                  The Spring framework provides factory classes based on the follow-
                                     context to the ENC                                           ing abstract classes that you use to develop Spring-enabled EJBs.
 unitName         String             Name of the persistence unit      “”
                                                                                                  Support Class                     Purpose

The persistence-unit-ref is similar to @PersistenceUnit that is                                   AbstractStatelessSessionBean      Used for Spring-enabled stateless session
                                                                                                                                    beans.
used to define references to a persistence unit (i.e., entity
                                                                                                  AbstractStatefulSessionBean       Used for Spring-enabled stateful session
manager factory).                                                                                                                   beans.

                                                                                                  AbstractJMSMessageDrivenBean      Used for Spring-enabled JMS message-
 Element/Attribute Name             Description                                                                                     driven beans.
 persistence-unit-ref-name          The name used to bind the referenced persistence              AbstractMessageDrivenBean         Used for Spring-enabled connector-based
                                    unit (EntityManagerFactory) to the ENC. Same                                                    MDBs.
                                    as the name element in the @PersistenceUnit
                                    annotation.
                                                                                                  To use a Spring factory class to access a Spring bean, your EJB 3
 persistence-unit-name              Name of the persistence unit referenced.                      bean class must implement the onEjbCreate() method.
 injection-target                   Target where the EntityManagerFactory is injected             Below is the PlaceBidBean EJB 3 example transformed into a
                                    when dependency injection is used.
                                                                                                  Spring-enabled stateless session bean. Here the PlaceBidBean


                                                                               DZone, Inc.   |   www.dzone.com
6
                                                                                                                                                                                        Dependency Injection in EJB 3
                   tech facts at your fingertips




           Injecting Spring Beans in EJB 3, continued                                                                              up is performed to obtain the path for the bean factory by using
                                                                                                                                   an environment entry named ejb/BeanFactoryPath. So you have
           acts as a façade and delegates the actual business logic to the
                                                                                                                                   to define it in the EJB deployment descriptor for the EJB:
           PlaceBidServiceBean. The PlaceBidServiceBean is a Spring
                                                                                                                                   <session>
           POJO that may use the full power of the Spring framework.
                                                                                                                                    <display-name>PlaceBid</display-name>
           @Stateless(name = “PlaceBid”)                                                                                            <ejb-name>PlaceBid</ejb-name>
           public class PlaceBidBean extends AbstractStatelessSessionBean                                                           <env-entry>
           implements PlaceBid {                                                                                                       <env-entry-name>ejb/BeanFactoryPath</env-entry-name>
                                                                                                                                       <env-entry-type>java.lang.String</env-entry-type>
               private BidServiceBean bidService;
                                                                                                                                       <env-entry-value>/actionBazaar-service.xml</env-entry-value>
               public PlaceBidBean() {
                                                                                                                                    </env-entry>
               }
                                                                                                                                   </session>
                   protected void onEjbCreate() {
                   bidService =                                                                                                    Although EJB 3 made deployment descriptor optional there are
                   (BidServiceBean) getBeanFactory().getBean(“bidService”);                                                        a few cases where you still have to use it. In our example we’ve
               }                                                                                                                   set the env-entry-value for the ejb/BeanFactoryPath environment
               public Long addBid(String userId, Long itemId, Double bidPrice) {                                                   variable at /actionBazaar-service.xml. So you have to package
                 return bidService.addBid(userId, itemId, bidPrice);                                                               the EJB classes, Spring classes, and Spring configuration file into
               }
                                                                                                                                   your ejb-jar package. The Spring bean factory (configuration file)
           When an EJB instance is created (when a client invokes an EJB),                                                         defines the Spring beans. Refer to the Spring Configuration
           the onEjbCreate method is invoked automatically. A JNDI look-                                                           Refcard for details about Spring configuration.



      ABOUT THE AUTHOR                                                                                                                                                  RECOMMENDED BOOK

                                        Debu Panda                                                                                                                                            EJB 3 in Action starts with
                                        Debu Panda is a Senior Principal Product Manager of the System Management                                                                             a tour of the EJB 3 land-
                                        Products team at Oracle, where he drives development of the middleware                                                                                scape, then moves quickly
                                        management product. He has more than 15 years of experience in the IT                                                                                 into core topics like building
                                        industry and has published numerous articles on enterprise Java technologies                                                                          business logic with session
                                        in several magazines and has presented at many conferences. His J2EE-focused                                                                          and message-driven beans.
                                        weblog can be found at debupanda.com.                                                                                                                 It covers the JPA along with
                                                                                                                                                                                              practical code samples,
      Publications                                                        Articles                                                                                                            design patterns, performance
      n	   EJB3 in Action, 2007                                           n	   Spring and Java EE 5, Part 1                                                                tuning tips, and best practices for building and
                                                                                                                                                                           deploying scalable applications.
      Projects                                                            n	   Spring and Java EE 5, Part 2
      n	   Oracle Application Server                                      n	   ONJava.com—Standardizing Java Persistence
      Blog                                                                     with the EJB3 Java Persistence API                                                                          BUY NOW
      n	   Personal weblog: debupanda.com                                 n	   Migrating JDBC DAO to EJB3                                                                 books.dzone.com/books/ejb3-in-action



 Subscribe Now for FREE! refcardz.com
 Upcoming Refcardz:                                                                                                                                                                  FREE
 n		
          RSS and Atom                                              n		
                                                                          Design Patterns
 n		
          Flexible Rails:                                           n		
                                                                          MS Silverlight 2
          Flex 3 on Rails 2                                               NetBeans IDE 6
                                                                    n		
                                                                                                                                                                       Getting
 n	
          C#                                                              Java Editor                                                                                  Started with
 n	
          GlassFish Application Server                              n		
                                                                          Groovy                                                                                       Ajax
 n
     		   jQuery Selectors                                          n		
                                                                          Apache Struts 2                                                                                                  GWT Style, Configuration
                                                                                                                                                                                               and JSNI Reference


                                                                                                                              DZone, Inc.
                                                                                                                                                                                       ISBN-13: 978-1-934238-03-5
                                                                                                                              1251 NW Maynard
                                                                                                                                                                                       ISBN-10: 1-934238-03-1
                                                                                                                              Cary, NC 27513                                                                      50795
                                                                                                                              888.678.0399
The DZone Network is a group of free online services that aim to                                                              919.678.0300
satisfy the information needs of software developers and architects.                                                          Refcardz Feedback Welcome
From news, blogs, tutorials, source code and more, DZone offers
                                                                                                                                                                                                                               $7.95




                                                                                                                              refcardz@dzone.com
everything technology professionals need to succeed.                                                                          Sponsorship Opportunities                              9 781934 238035
To quote PC magazine, “DZone is a developer’s dream.”                                                                         sales@dzone.com

Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic,                               Version 1.0
mechanical, photocopying, or otherwise, without prior written permission of the publisher.

More Related Content

Viewers also liked

Canstruction
CanstructionCanstruction
Canstructionreynolds
 
Corejava Online 100
Corejava Online 100Corejava Online 100
Corejava Online 100reynolds
 
Some Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The WorldSome Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The Worldreynolds
 
The Water Cycle
The Water CycleThe Water Cycle
The Water Cyclereynolds
 
Fattest Athlete In The World
Fattest Athlete In The WorldFattest Athlete In The World
Fattest Athlete In The Worldreynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
Brain Learn
Brain  LearnBrain  Learn
Brain Learnreynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
Halloween Art
Halloween ArtHalloween Art
Halloween Artreynolds
 
Snake Catchers In Africa
Snake Catchers In AfricaSnake Catchers In Africa
Snake Catchers In Africareynolds
 
Three Thing In The Life
Three Thing In The LifeThree Thing In The Life
Three Thing In The Lifereynolds
 

Viewers also liked (11)

Canstruction
CanstructionCanstruction
Canstruction
 
Corejava Online 100
Corejava Online 100Corejava Online 100
Corejava Online 100
 
Some Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The WorldSome Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The World
 
The Water Cycle
The Water CycleThe Water Cycle
The Water Cycle
 
Fattest Athlete In The World
Fattest Athlete In The WorldFattest Athlete In The World
Fattest Athlete In The World
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Brain Learn
Brain  LearnBrain  Learn
Brain Learn
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Halloween Art
Halloween ArtHalloween Art
Halloween Art
 
Snake Catchers In Africa
Snake Catchers In AfricaSnake Catchers In Africa
Snake Catchers In Africa
 
Three Thing In The Life
Three Thing In The LifeThree Thing In The Life
Three Thing In The Life
 

Similar to Ejb3online Final 060208v2

Similar to Ejb3online Final 060208v2 (20)

Introcution to EJB
Introcution to EJBIntrocution to EJB
Introcution to EJB
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Ejbandjsp 200119145750
Ejbandjsp 200119145750Ejbandjsp 200119145750
Ejbandjsp 200119145750
 
EJB3 Basics
EJB3 BasicsEJB3 Basics
EJB3 Basics
 
Ejb and jsp
Ejb and jspEjb and jsp
Ejb and jsp
 
Unite5-EJB-2019.ppt
Unite5-EJB-2019.pptUnite5-EJB-2019.ppt
Unite5-EJB-2019.ppt
 
EJB Interview Questions
EJB Interview QuestionsEJB Interview Questions
EJB Interview Questions
 
The Complete Spring Tutorial
The Complete Spring TutorialThe Complete Spring Tutorial
The Complete Spring Tutorial
 
Ejb (1)
Ejb (1)Ejb (1)
Ejb (1)
 
Al rihieli persistence
Al rihieli persistenceAl rihieli persistence
Al rihieli persistence
 
Jpa basics
Jpa basicsJpa basics
Jpa basics
 
Ejb
EjbEjb
Ejb
 
Real world java_ee_patterns
Real world java_ee_patternsReal world java_ee_patterns
Real world java_ee_patterns
 
Jsf+ejb 50
Jsf+ejb 50Jsf+ejb 50
Jsf+ejb 50
 
Ejb course in-mumbai
Ejb course in-mumbaiEjb course in-mumbai
Ejb course in-mumbai
 
Java EE 7 - Into the Cloud
Java EE 7 - Into the CloudJava EE 7 - Into the Cloud
Java EE 7 - Into the Cloud
 
JUG Darmstadt - Java EE 7 - Auf in die Wolken!
JUG Darmstadt - Java EE 7 - Auf in die Wolken!JUG Darmstadt - Java EE 7 - Auf in die Wolken!
JUG Darmstadt - Java EE 7 - Auf in die Wolken!
 
Jpa
JpaJpa
Jpa
 
Oracle ADF Overview
Oracle ADF OverviewOracle ADF Overview
Oracle ADF Overview
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 

More from reynolds

Tsunami Before & After
Tsunami Before & AfterTsunami Before & After
Tsunami Before & Afterreynolds
 
America chooses barack obama
America chooses barack obamaAmerica chooses barack obama
America chooses barack obamareynolds
 
Obama Biden
Obama BidenObama Biden
Obama Bidenreynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
Vote For Change
Vote For ChangeVote For Change
Vote For Changereynolds
 
ObamaShirts
ObamaShirtsObamaShirts
ObamaShirtsreynolds
 
Obama+Presidential+Seal
Obama+Presidential+SealObama+Presidential+Seal
Obama+Presidential+Sealreynolds
 
Barack Obama Phots Gallery
Barack Obama Phots GalleryBarack Obama Phots Gallery
Barack Obama Phots Galleryreynolds
 
Learn to live
Learn to liveLearn to live
Learn to livereynolds
 
MANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSMANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSreynolds
 
Artistic Airplanes
Artistic AirplanesArtistic Airplanes
Artistic Airplanesreynolds
 
Web 20 Business Models
Web 20 Business ModelsWeb 20 Business Models
Web 20 Business Modelsreynolds
 
Girls Just Wanna Have Fun
Girls Just Wanna Have FunGirls Just Wanna Have Fun
Girls Just Wanna Have Funreynolds
 
pumpkin faces
pumpkin facespumpkin faces
pumpkin facesreynolds
 
Palin Clothes Spending Has Dems Salivating Republicans Digusted
Palin Clothes Spending Has Dems Salivating Republicans DigustedPalin Clothes Spending Has Dems Salivating Republicans Digusted
Palin Clothes Spending Has Dems Salivating Republicans Digustedreynolds
 
Funny Helicopter Pictures
Funny Helicopter PicturesFunny Helicopter Pictures
Funny Helicopter Picturesreynolds
 
Poverty Slide Show
Poverty Slide ShowPoverty Slide Show
Poverty Slide Showreynolds
 
Poverty Imges
Poverty ImgesPoverty Imges
Poverty Imgesreynolds
 

More from reynolds (18)

Tsunami Before & After
Tsunami Before & AfterTsunami Before & After
Tsunami Before & After
 
America chooses barack obama
America chooses barack obamaAmerica chooses barack obama
America chooses barack obama
 
Obama Biden
Obama BidenObama Biden
Obama Biden
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Vote For Change
Vote For ChangeVote For Change
Vote For Change
 
ObamaShirts
ObamaShirtsObamaShirts
ObamaShirts
 
Obama+Presidential+Seal
Obama+Presidential+SealObama+Presidential+Seal
Obama+Presidential+Seal
 
Barack Obama Phots Gallery
Barack Obama Phots GalleryBarack Obama Phots Gallery
Barack Obama Phots Gallery
 
Learn to live
Learn to liveLearn to live
Learn to live
 
MANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSMANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESS
 
Artistic Airplanes
Artistic AirplanesArtistic Airplanes
Artistic Airplanes
 
Web 20 Business Models
Web 20 Business ModelsWeb 20 Business Models
Web 20 Business Models
 
Girls Just Wanna Have Fun
Girls Just Wanna Have FunGirls Just Wanna Have Fun
Girls Just Wanna Have Fun
 
pumpkin faces
pumpkin facespumpkin faces
pumpkin faces
 
Palin Clothes Spending Has Dems Salivating Republicans Digusted
Palin Clothes Spending Has Dems Salivating Republicans DigustedPalin Clothes Spending Has Dems Salivating Republicans Digusted
Palin Clothes Spending Has Dems Salivating Republicans Digusted
 
Funny Helicopter Pictures
Funny Helicopter PicturesFunny Helicopter Pictures
Funny Helicopter Pictures
 
Poverty Slide Show
Poverty Slide ShowPoverty Slide Show
Poverty Slide Show
 
Poverty Imges
Poverty ImgesPoverty Imges
Poverty Imges
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Ejb3online Final 060208v2

  • 1. Subscribe Now for FREE! refcardz.com tech facts at your fingertips CONTENTS INCLUDE: What is EJB3? Dependency Injection in EJB 3 n n Resource Injection n Injection of EJB References n Injecting JPA Resources n Injecting Spring Beans in EJB 3 n Hot Tips and more... By Debu Panda WHAT IS EJB 3? DEPENDENCY INJECTION IN EJB 3 Enterprise JavaBeans (EJB) is a platform for building portable, With EJB 3, dependency injection has greatly simplified accessing reusable, and scalable business applications using the Java both EJB resources—such as JDBC DataSource, JMS Objects, programming language. Since its initial incarnation, EJB has and JPA Entity Manager—and services—such as Timer, User been touted as a component model or framework that lets you Transaction, and Web Services. You will find this Refcard useful when building enterprise Java applications with EJB 3 and JPA. build enterprise Java applications without having to reinvent It lists all metadata annotations, describes them and provides services such as transactions, security, and automated persistence examples. It also provides descriptions for XML elements that for building an application. you can use for injection. EJB 3 greatly simplifies development by adopting a POJO Most enterprise Java applications use external resources programming model. As shown in the following figure an and services such as Data Source, EJB, or web services. EJB 3 annotation transforms a simple POJO to an EJB. makes using resources and services simpler by implementing dependency injection. Dependency injection allows you to simply declare component J + @ = dependencies and let the EJB container deal with the complexities www.dzone.com of instantiating, initializing, and sequencing resources and supplying service or resource references to clients as required. POJO Annotation EJB Development frameworks like Spring framework originally popularized dependency injection. EJB 3 not only simplifies development of session and message In EJB 3, you may think of dependency injection as the inverse of driven beans but it also radically simplifies the persistence JNDI. It is the responsibility of the container to inject an object model by implementing a simplified Object-Relational Mapping based on the dependency declaration. The figure below com- approach similar to Oracle TopLink and JBoss Hibernate as a pares dependency injection with JNDI. part of the Java Persistence API. Note that JPA replaces EJB 2 CMP Entity beans in the EJB 3 spec, while being available outside of the Java EE container. Resources Lookup Following is an example of a simple EJB 3 Stateless session bean. EJB JNDI lookup import javax.ejb.Stateless; Beans import ejb3inaction.example.persistence.Bid; Dependency Injection in EJB 3 @Stateless public class PlaceBidBean implements PlaceBid { Resources Dependency ... injection Container Injection EJB public PlaceBidBean() {} Beans public Bid addBid(Bid bid) { System.out.println(“Adding bid, bidder ID=” + bid.getBidderID() Get More Refcardz + “, item ID=” + bid.getItemID() (They’re free!) + “, bid amount=” + bid.getBidAmount() + “.”); n Authoritative content return save(bid); n Designed for developers } n Written by top experts ... n Latest tools & technologies } n Hot tips & examples import javax.ejb.Local; n Bonus content online import ejb3inaction.example.persistence.Bid; n New issue every 1-2 weeks @Local public interface PlaceBid { Subscribe Now for FREE! Bid addBid(Bid bid); Refcardz.com } DZone, Inc. | www.dzone.com
  • 2. 2 Dependency Injection in EJB 3 tech facts at your fingertips The following annotations can be used in a field or a setter method DEPENDENCY INJECTION IN EJB 3 continued for dependency injection. However, these annotations may also be applied at the class level for defining dependencies and then used with JNDI look up. Note that annotations and descriptors are not Hot mutually exclusive. In fact, you can use both Annotations Usage Components that Tip can use together. Deployment descriptor entries override javax.annotation.Resource Dependency injection EJB, Web, configuration values specified using metadata of resources such as Application Client DataSource, and JMS annotations. objects javax.ejb.EJB Dependency injection EJB, Web, of Session beans Application Client You can use either metadata annotations or XML descriptors javax.xml.ws.WebServiceRef Dependency injection EJB, Web, to use dependency injection. of Web services Application Client Refer to the following Java EE 5 specifications and XML schema javax.persistence. Dependency injection EJB, Web PersistenceContext of container-managed for more information on dependency injection. EntityManager JSR 220 javax.persistence. Dependency injection EJB, Web Enterprise JavaBeans 3.0: PersistenceUnit of EntityManagerFactory http://www.jcp.org/en/jsr/detail?id=220 JSR 224 RESOURCE INJECTION Java API for XML-Based Web Services (JAX-WS) 2.0: http://jcp.org/en/jsr/detail?id=224 javax.annotation.Resource The @Resource annotation is used to inject any of the following: JSR 250: JDBC data sources, JMS connection factories, JMS destinations, Common Annotations for the Java Platform: mail resource, environment entries, timer service, UserTransaction, http://www.jcp.org/en/jsr/detail?id=250 and EJBContext. Schema for EJB 3 deployment descriptor: The following table shows attributes for the @Resource annotation. http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd Schema that defines common schema components: Parameter Type Description Default http://java.sun.com/xml/ns/javaee/javaee_5.xsd authentication enum The type of authentication CONTAINER Type Authentication required for accessing the Dependency injection is supported only on managed classes Type resource. The CONTAINER {CONTAINER, value means that the and not on regular POJO. APPLICATION} container’s security context is used for the resource. The APPLICATION value means Dependency injection is supported only on that authentication for the Hot managed classes such as Session Beans or In- resource must be provided Tip by the application. terceptors and not on regular POJO. Hence you name String The referred resources is “” bound under this name in cannot use injection on helper classes. the enviornment-naming context as java:comp/ env/<Name> The following table depicts what type of managed classes can type Object Type of the resource Object.class inject what objects. being referenced. Example: javax.sql.DataSource Resources Stateless Stateful MDB Interceptors shareable Boolean Specifies whether the True JDBC DataSource Yes Yes Yes Yes resource can be shared. JMS Destinations, Yes Yes Yes Yes description String The description of the “” Connection Factories resource. mappedName String A vendor-specific name “” Mail Resources Yes Yes Yes Yes that the resource may be UserTransaction Yes Yes Yes Yes mapped to, as opposed to the JNDI name. Environment Entries Yes Yes Yes Yes EJBContext Yes Yes Yes No You can inject a resource at the field or setter method level. Timer Service Yes No Yes No The following example shows data source injection at the field level: @Resource(name=”jdbc/ActionBazaarDS”) Web Service reference Yes Yes Yes Yes private DataSource dataSource; EnityManager, Yes Yes Yes Yes EntityManagerFactory The following code shows data source injection at the setter method level: Java EE 5 introduced several metadata annotations as part of private DataSource dataSource; JSR 250. Although primarily geared toward EJB, these annota- @Resource(name=”jdbc/ActionBazaarDB”) public void setDataSource(DataSource dataSource) { tions also apply to Java EE components such as Servlets, JSF this.dataSource = dataSource; managed beans, and application clients. } DZone, Inc. | www.dzone.com
  • 3. 3 Dependency Injection in EJB 3 tech facts at your fingertips resource-env-ref RESOURCE INJECTION continued The resource-env-ref is used to specify references to JMS destination resources such as a Queue or Topic. Element/Attribute Name Description Although setter injection might seem like a Hot resource-env-ref-name The name used to bind the referenced JMS Tip little more work, it provides a couple of distinct destination to the ENC. Same as the name element in the @Resource annotation. advantages. First, it is easier to unit-test by mapped-name A vendor-specific global JNDI name for the invoking the public setter method from a testing referenced JMS destination. framework like JUnit. Second, it is easier to put resource-env-type Type of JMS destination referenced, such as javax. jms.Queue or javax.jms.Topic. initialization code in the setter if you need it. injection-target Target where the referenced destination is injected when dependency injection is used. EJB 3 allows you to explicitly specify a global JNDI name using <resource-env-ref> the mappedName parameter of the @Resource annotation. For <resource-env-ref-name>jms/OrderBillingQueue</resource-env-ref-name> example, if you’re using the Oracle Application Server and you <resource-env-ref-type> have a data source with a global JNDI name of jdbc/OracleDS, javax.jms.Destination you can specify the resource mapping as follows: </resource-env-ref-type> <injection-target> @Resource(name=”jdbc/ActionBazaarDS”, mappedName=”jdbc/ <injection-target-class> OracleDS”) ejb3inaction.example.buslogic.PlaceOrderBean private javax.jdbc.DataSource myDB; </injection-target-class> <injection-target-name>billingQueue</injection-target-name> XML elements to define Resource Injection </injection-target> </resource-env-ref> If you are using deployment descriptor (ejb-jar.xml) instead of annotations, then you must use resource-ref, resource-env-ref env-entry or env-entry XML elements to define dependencies. The env-entry defines environment entries for an EJB. resource-ref Element/Attribute Name Description The resource-ref is used to specify resource references. env-entry-name The name used in the environment entry in Example: data source and JMS connection factories. the ENC. Same as the name element in the @Resource annotation. Element/Attribute Name Description env-entry-type Type of the env entry used. Legal types are java.lang.Boolean, java.lang.Byte, java.lang. res-ref-name The name used to bind the referenced resource Character, java.lang.String, java.lang.Short, into the ENC. Same as the name element in the java.lang.Integer, java.lang.Long, java.lang.Float, @Resource annotation. and java.lang.Double. mapped-name A vendor-specific global JNDI name for the env-entry-value Value specified for the environment entry. referenced resource. injection-target Target where the referenced destination is res-type Fully qualified class of the type of resource injected when dependency injection is used. referenced. Example: javax.sql.DataSource. res-auth Authentication type for the resource. Valid values The injection-target defines the name of a class and a name are Container or Application. (field or property) within that class into which a resource, res-sharing-scope Specifies whether multiple beans can share EJB, or entity manager should be injected as we saw in the the resource. Valid values are Shareable and above examples. Unshareable injection-target Target where the referenced resource is injected Element/Attribute Name Description when dependency injection is used. injection-target-class The fully qualified name of the class into which a resource, EJB, or entity manager should be injected. <resource-ref> injection-target-name Name of the injection target, i.e., the name of the <res-ref-name>jdbc/ActionBazaarDS</res-ref-name> property or field in the injection target class. <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> INJECTION OF SESSION EJB REFERENCES <injection-target> Like resource injection, you can inject Session bean references <injection-target-class> into another EJB or other managed class using annotations actionbazaar.buslogic.BidManagerBean</injection-target-class> or deployment XML. If you prefer annotations you can use <injection-target-name>dataSource</injection-target-name> @javax.ejb.EJB annotations to inject either remote or local </injection-target> EJB references. Using deployment XML, you can inject </resource-ref> remote EJB references with ejb-ref and local EJB references with ejb-local-ref. DZone, Inc. | www.dzone.com
  • 4. 4 Dependency Injection in EJB 3 tech facts at your fingertips @javax.ejb.EJB Injects a session bean reference into a field or method. EJB 3 specification does not require Hot injecting references of remote EJB into a Parameter Type Description Default Tip different instance of container. For example name String The name used to bind the “” referenced EJB to the ENC. if you have an EJB with a remote interface deployed into an instance of a container, beanInterface Class The bean interface used to access Object. the EJB class EJB 3 specification does not require inject- mappedName String Type of the resource being referenced. “” ing instance of that EJB into another EJB Example: javax.sql.DataSource deployed in another container. beanName String Specifies whether the resource can “” be shared. description String INJECTINg JPA RESOURCES @EJB(name=”BidManagerRemote”) The JPA EntityManager is the bridge between the OO and private BidManager bidManager; relational worlds as depicted in the following figure. You must not inject a Stateful session bean Hot Save SQL into a stateless object, such as a stateless Object EntityManager Tip Relational Database Retrieve Results session bean or servlet that may be shared by multiple concurrent clients (you should use JNDI in such cases instead). JPA supports two types of EntityManager: container-managed However, injecting an instance of a state- and application-managed. As the name suggests the lifecycle less session bean into a stateful session of the container manages container-managed EntityManager bean is perfectly legal. whereas the lifecycle (creation, destruction) is performed by application. An application-managed EntityManager is created from an EntityManagerFactory. ejb-local-ref Injecting container-managed EntityManager Used to specify a dependency on the local interface of a You can inject a container-managed EntityManager (either session bean. transaction scoped or extended) using @javax.persistence. Element/Attribute Name Description PersistenceContext annotation. ejb-ref-name The name used to bind the referenced EJB to @javax.persistence.PersistenceContext the ENC. Same as the name element in the @EJB annotation. ejb-ref-name must be specified. The following table defines the parameters/attributes of this annotation. ejb-link The name of the target enterprise bean. This optional setting is used to link an EJB reference to Parameter Type Description Default a target enterprise bean. name String The name used to bind “” local The EJB 3 local business interface. the referenced persistence context to the ENC ref-type The EJB reference type, i.e. “session”. unitName String Name of the persistence unit “” injection-target Target where the EJB reference is injected when referenced dependency injection is used. type Persistence Type of persistence context, TRANSACTION ContextType i.e., Transaction or Extended. ejb-ref Extended is supported only in stateful session beans. Used to specify a dependency on the remote interface of a session bean. properties Persistence A name value-pair of vendor- {} Property[] specific persistence properties Element/Attribute Name Description You can inject a transaction scoped EntityManager as follows: ejb-ref-name The name used to bind the referenced EJB to the ENC. Same as the name element in the @EJB @PersistenceContext(unitName=”actionBazaar”) annotation. ejb-ref-name must be specified. private EntityManager entityManager; ejb-link The name of the target enterprise bean. This An extended scoped EntityManager can only used in a stateful optional setting is used to link an EJB reference session bean as in the following example: to a target enterprise bean. @Stateful remote The EJB 3 remote business interface type. @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) ref-type The EJB reference type, i.e. “session”. public class PlaceOrderBean implements PlaceOrder { @PersistenceContext(unitName = “actionBazaar”, type = injection-target Target where the EJB reference is injected when PersistenceContextType.EXTENDED) dependency injection is used. EntityManager em; DZone, Inc. | www.dzone.com
  • 5. 5 Dependency Injection in EJB 3 tech facts at your fingertips Injecting JPA Resources, continued INJECTINg WEB SERvICE REFERENCES The persistence-context-ref is similar to @PersistenceContext; it defines references to a container-managed entity manager. @javax.xml.ws.WebServiceRef Element Description Element/Attribute Name Description name The JNDI name for the web service. persistence-context-ref- The name used to bind the referenced persistence name context to the ENC. Same as the name element in wsdlLocation The WSDL location for the service. If not specified, then it is derived from the referenced service class. the @PersistenceContext annotation. type The Java type of the resource. persistence-unit-name Name of the persistence unit referenced. value The service class, always a type extending javax.xml. persistence-context-type Type of persistence context, i.e., Transaction or ws.Service. Extended. Extended is supported only in stateful mappedName Vendor-specific global JNDI name for the service. session beans. persistence-property A name value-pair of vendor-specific persistence You can inject an endpoint interface as follows: properties. @WebServiceRef(TrackDeliveryService.class) injection-target Target where the EntityManager is injected when private TrackDeliverySEI deliveryService; dependency injection is used. You can inject a service interface as follows: <persistence-context-ref> @WebServiceRef private TrackingService service; <persistence-context-ref-name> ActionBazaar service-ref </persistence-context-ref-name> The service-ref XML element is used to specify dependency on a <persistence-unit-name>actionBazaar</persistence-unit-name> web service if you are using deployment descriptor. The following <persistence-context-type>Transaction</persistence-context-type> table contains only the elements that are used from EJB clients. <injection-target> <injection-target-class> Element/Attribute Name Description ejb3inaction.example.buslogic.PlaceBidBean service-ref-name The name used to bind the referenced web service </injection-target-class> into the ENC. Same as the name element in the @ WebServiceRef annotation. <injection-target-name>em</injection-target-name> </injection-target> service-interface Fully qualified class for the JAX-WS service interface the client depends on., i.e. javax.xml.rpc.Service. </persistence-context-ref> service-ref-type Type of service that will be returned. Injecting EntityManagerFactory wsdl-file The URL location of the WSDL. @javax.persistence.PersistenceUnit handler-chains Defines handler chain. @Stateless injection-target Target where the web service reference is injected when dependency injection is used. public class ItemManagerBean implements ItemManager { @PersistenceUnit The detailed schema for the service-ref can be found online at private EntityManagerFactory entityManagerFactory; java.sun.com/xml/ns/javaee/javaee_web_services_client_1_2.xsd. private EntityManager entityManager; @PostConstruct public void initialize() { INJECTINg SPRINg BEANS IN EJB 3 entityManager = entityManagerFactory.createEntityManager(); } The Spring Framework is one of the driving forces behind popular- } izing the POJO programming model and dependency injection. In this section we will examine how you can inject and use Spring Parameter Type Description Default POJOs into EJB 3 Session beans or Message Driven Beans. name String The name used to bind “” the referenced persistence The Spring framework provides factory classes based on the follow- context to the ENC ing abstract classes that you use to develop Spring-enabled EJBs. unitName String Name of the persistence unit “” Support Class Purpose The persistence-unit-ref is similar to @PersistenceUnit that is AbstractStatelessSessionBean Used for Spring-enabled stateless session beans. used to define references to a persistence unit (i.e., entity AbstractStatefulSessionBean Used for Spring-enabled stateful session manager factory). beans. AbstractJMSMessageDrivenBean Used for Spring-enabled JMS message- Element/Attribute Name Description driven beans. persistence-unit-ref-name The name used to bind the referenced persistence AbstractMessageDrivenBean Used for Spring-enabled connector-based unit (EntityManagerFactory) to the ENC. Same MDBs. as the name element in the @PersistenceUnit annotation. To use a Spring factory class to access a Spring bean, your EJB 3 persistence-unit-name Name of the persistence unit referenced. bean class must implement the onEjbCreate() method. injection-target Target where the EntityManagerFactory is injected Below is the PlaceBidBean EJB 3 example transformed into a when dependency injection is used. Spring-enabled stateless session bean. Here the PlaceBidBean DZone, Inc. | www.dzone.com
  • 6. 6 Dependency Injection in EJB 3 tech facts at your fingertips Injecting Spring Beans in EJB 3, continued up is performed to obtain the path for the bean factory by using an environment entry named ejb/BeanFactoryPath. So you have acts as a façade and delegates the actual business logic to the to define it in the EJB deployment descriptor for the EJB: PlaceBidServiceBean. The PlaceBidServiceBean is a Spring <session> POJO that may use the full power of the Spring framework. <display-name>PlaceBid</display-name> @Stateless(name = “PlaceBid”) <ejb-name>PlaceBid</ejb-name> public class PlaceBidBean extends AbstractStatelessSessionBean <env-entry> implements PlaceBid { <env-entry-name>ejb/BeanFactoryPath</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> private BidServiceBean bidService; <env-entry-value>/actionBazaar-service.xml</env-entry-value> public PlaceBidBean() { </env-entry> } </session> protected void onEjbCreate() { bidService = Although EJB 3 made deployment descriptor optional there are (BidServiceBean) getBeanFactory().getBean(“bidService”); a few cases where you still have to use it. In our example we’ve } set the env-entry-value for the ejb/BeanFactoryPath environment public Long addBid(String userId, Long itemId, Double bidPrice) { variable at /actionBazaar-service.xml. So you have to package return bidService.addBid(userId, itemId, bidPrice); the EJB classes, Spring classes, and Spring configuration file into } your ejb-jar package. The Spring bean factory (configuration file) When an EJB instance is created (when a client invokes an EJB), defines the Spring beans. Refer to the Spring Configuration the onEjbCreate method is invoked automatically. A JNDI look- Refcard for details about Spring configuration. ABOUT THE AUTHOR RECOMMENDED BOOK Debu Panda EJB 3 in Action starts with Debu Panda is a Senior Principal Product Manager of the System Management a tour of the EJB 3 land- Products team at Oracle, where he drives development of the middleware scape, then moves quickly management product. He has more than 15 years of experience in the IT into core topics like building industry and has published numerous articles on enterprise Java technologies business logic with session in several magazines and has presented at many conferences. His J2EE-focused and message-driven beans. weblog can be found at debupanda.com. It covers the JPA along with practical code samples, Publications Articles design patterns, performance n EJB3 in Action, 2007 n Spring and Java EE 5, Part 1 tuning tips, and best practices for building and deploying scalable applications. Projects n Spring and Java EE 5, Part 2 n Oracle Application Server n ONJava.com—Standardizing Java Persistence Blog with the EJB3 Java Persistence API BUY NOW n Personal weblog: debupanda.com n Migrating JDBC DAO to EJB3 books.dzone.com/books/ejb3-in-action Subscribe Now for FREE! refcardz.com Upcoming Refcardz: FREE n RSS and Atom n Design Patterns n Flexible Rails: n MS Silverlight 2 Flex 3 on Rails 2 NetBeans IDE 6 n Getting n C# Java Editor Started with n GlassFish Application Server n Groovy Ajax n jQuery Selectors n Apache Struts 2 GWT Style, Configuration and JSNI Reference DZone, Inc. ISBN-13: 978-1-934238-03-5 1251 NW Maynard ISBN-10: 1-934238-03-1 Cary, NC 27513 50795 888.678.0399 The DZone Network is a group of free online services that aim to 919.678.0300 satisfy the information needs of software developers and architects. Refcardz Feedback Welcome From news, blogs, tutorials, source code and more, DZone offers $7.95 refcardz@dzone.com everything technology professionals need to succeed. Sponsorship Opportunities 9 781934 238035 To quote PC magazine, “DZone is a developer’s dream.” sales@dzone.com Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, Version 1.0 mechanical, photocopying, or otherwise, without prior written permission of the publisher.