Dependency Injection in EJB 3 - DZone Refcardz
Dependency Injection in EJB 3 - DZone Refcardz
DZone
>
Refcardz
>
Dependency Injection in EJB 3
Refcard #006
Written By
Debu Panda
Director, Product Management, Oracle
https://dzone.com/asset/download/10 1/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
Table of Contents
►
What is EJB 3?
►
Dependency Injection in EJB 3
►
Resource Injection
►
Injection of Session EJB References
►
Injecting JPA Resources
►
Injecting Web Service References
►
Injecting Spring Beans in EJB 3
Section 1
What is EJB 3?
Enterprise JavaBeans (EJB) is a platform for building portable, reusable, and scalable
business applications using the Java programming language. Since its initial
incarnation, EJB has been touted as a component model or framework that lets you
build enterprise Java applications without having to reinvent services such as
transactions, security, and automated persistence for building an application.
EJB 3 not only simplifies development of session and message driven beans but it
also radically simplifies the persistence model by implementing a simplified Object-
Relational Mapping approach similar to Oracle TopLink and JBoss Hibernate as a 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.
https://dzone.com/asset/download/10 2/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
1 import javax.ejb.Stateless;
2 import ejb3inaction.example.persistence.Bid;
3 @Stateless
4 public class PlaceBidBean implements PlaceBid {
5 ...
6 public PlaceBidBean() {}
7 public Bid addBid(Bid bid) {
8 System.out.println("Adding bid, bidder ID="
9 +
0 bid.getBidderID()
1 + ", item ID=" + bid.getItemID()
2 + ", bid amount="
3 + bid.getBidAmount() + ".");
4 r
5 eturn save(bid);
6 }
7 ...
8 }
9 import javax.ejb.Local;
0 import ejb3inaction.example.persistence.Bid;
1 @Local public interface PlaceBid {
2 Bid addBid(Bid bid);
3 }
4
Section 2
Most enterprise Java applications use external resources and services such as Data
Source, EJB, or web services. EJB 3 makes using resources and services simpler by
implementing dependency injection.
Dependency injection allows you to simply declare component dependencies and let
the EJB container deal with the complexities of instantiating, initializing, and
sequencing resources and supplying service or resource references to clients as
https://dzone.com/asset/download/10 3/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
In EJB 3, you may think of dependency injection as the inverse of JNDI. It is the
responsibility of the container to inject an object based on the dependency
declaration. The figure below compares dependency injection with JNDI.
Note that annotations and descriptors are not mutually exclusive. In fact, you can use
both together. Deployment descriptor entries override configuration values specified
using metadata annotations.
You can use either metadata annotations or XML descriptors to use dependency
injection.
Refer to the following Java EE 5 specifications and XML schema for more information
on dependency injection.
JSR 220
Enterprise JavaBeans 3.0:
http://www.jcp.org/en/jsr/detail?id=220
JSR 224
Java API for XML-Based Web Services (JAX-WS) 2.0:
http://jcp.org/en/jsr/detail?id=224
JSR 250:
https://dzone.com/asset/download/10 4/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
http://jcp.org/en/jsr/detail?id=224
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
http://java.sun.com/xml/ns/javaee/javaee_5.xsd
Dependency injection is supported only on managed classes and not on regular POJO.
The following table depicts what type of managed classes can inject what objects.
EntityManager,
Yes Yes Yes Yes
EntityManagerFactory
https://dzone.com/asset/download/10 5/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
The following annotations can be used in a field or a setter method for dependency
injection. However, these annotations may also be applied at the class level for
defining dependencies and then used with JNDI look up.
COMPONENTS
ANNOTATIONS USAGE
THAT CAN USE
EJB, Web,
javax.ejb.EJB Dependency injection of Session beans
Application Client
EJB, Web,
javax.xml.ws.WebServiceRef Dependency injection of Web services
Application Client
Dependency injection of
javax.persistence.PersistenceUnit EJB, Web
EntityManagerFactory
Section 3
Resource Injection
javax.annotation.Resource
The @Resource annotation is used to inject any of the following: JDBC data sources,
JMS connection factories, JMS destinations, mail resource, environment entries, timer
service, UserTransaction, and EJBContext.
The following example shows data source injection at the field level:
1 @Resource(name="jdbc/ActionBazaarDS")
2 private DataSource dataSource;
3
The following code shows data source injection at the setter method level:
Although setter injection might seem like a little more work, it provides a couple of
distinct advantages. First, it is easier to unit-test by invoking the public setter method
from a testing framework like JUnit. Second, it is easier to put initialization code in the
setter if you need it.
EJB 3 allows you to explicitly specify a global JNDI name using the mappedName
parameter of the @Resource annotation. For example, if you"re using the Oracle
Application Server and you have a data source with a global JNDI name of
jdbc/OracleDS, you can specify the resource mapping as follows:
resource-ref
The resource-ref is used to specify resource references. Example: data source and JMS
connection factories.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used to bind the referenced resource into the ENC. Same as the
res-ref-name
name element in the @Resource annotation.
Specifies whether multiple beans can share the resource. Valid values are
res-sharing-scope
Shareable and Unshareable
1 <resource-ref>
2 <res-ref-name>jdbc/ActionBazaarDS</res-ref-name>
3 <res-type>javax.sql.DataSource</res-type>
4 <res-auth>Container</res-auth>
5 <res-sharing-scope>Shareable</res-sharing-scope>
6 <injection-target>
7 <injection-tar
8 get-class>
9 actionbazaar.buslogic.BidManagerBean</injection-target-class>
0 <injection-tar
1 get-name>dataSource</injection-target-name>
2 </injection-target>
3 </resource-ref>
4
resource-env-ref
The resource-env-ref is used to specify references to JMS destination resources such
as a Queue or Topic.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used to bind the referenced JMS destination to the ENC. Same as
resource-env-ref-name
the name element in the @Resource annotation.
mapped-name A vendor-specific global JNDI name for the referenced JMS destination.
https://dzone.com/asset/download/10 8/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
1 <resource-env-ref>
2 <resource-env-ref-name>jms/OrderBillingQueue</resource-env-ref-name>
3 <resource-env-ref-type>
4 javax.jms.Destination
5 </resource-env-ref-type>
6 <injection-target>
7 <injection-target-class>
8 ejb3inaction.example.buslogic.PlaceOrderBean
9 </injection-target-class>
0 <injection-tar
1 get-name>billingQueue</injection-target-name>
2 </injection-target>
3 </resource-env-ref>
4
env-entry
The env-entry defines environment entries for an EJB.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used in the environment entry in the ENC. Same as the name
env-entry-name
element in the @Resource annotation.
The injection-target defines the name of a class and a name (field or property) within
that class into which a resource, EJB, or entity manager should be injected as we saw
in the above examples.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The fully qualified name of the class into which a resource, EJB, or entity
injection-target-class
manager should be injected.
https://dzone.com/asset/download/10 9/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
Name of the injection target, i.e., the name of the property or field in the
injection-target-name
injection target class.
Section 4
@javax.ejb.EJB
Injects a session bean reference into a field or method.
name String The name used to bind the referenced EJB to the ENC. ""
beanInterface Class The bean interface used to access the EJB Object.class
description String
1 @EJB(name="BidManagerRemote")
2 private BidManager bidManager;
3
You must not inject a Stateful session bean into a stateless object, such as a stateless
session bean or servlet that may be shared by multiple concurrent clients (you should
use JNDI in such cases instead). However, injecting an instance of a stateless session
bean into a stateful session bean is perfectly legal.
ejb-local-ref
Used to specify a dependency on the local interface of a session bean.
https://dzone.com/asset/download/10 10/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used to bind the referenced EJB to the ENC. Same as the name
ejb-ref-name
element in the @EJB annotation. ejb-ref-name must be specified.
The name of the target enterprise bean. This optional setting is used to link
ejb-link
an EJB reference to a target enterprise bean.
ejb-ref
Used to specify a dependency on the remote interface of a session bean.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used to bind the referenced EJB to the ENC. Same as the name
ejb-ref-name
element in the @EJB annotation. ejb-ref-name must be specified.
The name of the target enterprise bean. This optional setting is used to link
ejb-link
an EJB reference to a target enterprise bean.
EJB 3 specification does not require injecting references of remote EJB into a different
instance of container. For example if you have an EJB with a remote interface
deployed into an instance of a container, EJB 3 specification does not require injecting
instance of that EJB into another EJB deployed in another container.
Section 5
https://dzone.com/asset/download/10 11/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
@javax.persistence.PersistenceContext
The following table defines the parameters/attributes of this annotation.
1 @PersistenceContext(unitName="actionBazaar")
2 private EntityManager entityManager;
3
An extended scoped EntityManager can only used in a stateful session bean as in the
following example:
1 @Stateful
2 @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
3 public class PlaceOrderBean implements PlaceOrder {
4 @PersistenceContext(unitName = "actionBazaar", type =
5 PersistenceContextType.EXTENDED)
https://dzone.com/asset/download/10 12/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
6 EntityManager em;
7
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
persistence-context-ref- The name used to bind the referenced persistence context to the ENC.
name Same as the name element in the @PersistenceContext annotation.
1 <persistence-context-ref>
2 <persistence-conte
3 xt-ref-name>
4 A
5 ctionBazaar
6 </persistence-conte
7 xt-ref-name>
8 <persistence-unit-name>actionBazaar</persistence-unit-name>
9 <persistence-conte
0 xt-type>Transaction</persistence-context-type>
1 <injection-tar
2 get>
3 <injection-target-class>
4 ejb3inaction.example.buslogic.PlaceBidBean
5 </injection-target-class>
6 <injection-target-name>em</injection-target-name>
7 </injection-tar
8 get>
9 </persistence-context-ref>
0
Injecting EntityManagerFactory
@javax.persistence.PersistenceUnit
1 @Stateless
2 public class ItemManagerBean implements ItemManager {
3 @PersistenceUnit
4 private EntityManagerFactory entityManagerFactory;
5 private EntityManager entityManager;
6 @PostConstruct
https://dzone.com/asset/download/10 13/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
Section 6
The WSDL location for the service. If not specified, then it is derived from the referenced
wsdlLocation
service class.
1 @WebServiceRef(TrackDeliveryService.class)
2 private TrackDeliverySEI deliveryService;
3
https://dzone.com/asset/download/10 14/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
1 @WebServiceRef
2 private TrackingService service;
3
service-ref
The service-ref XML element is used to specify dependency on a web service if you
are using deployment descriptor. The following table contains only the elements that
are used from EJB clients.
ELEMENT/ATTRIBUTE
DESCRIPTION
NAME
The name used to bind the referenced web service into the ENC. Same as
service-ref-name
the name element in the @WebServiceRef annotation.
Fully qualified class for the JAX-WS service interface the client depends
service-interface
on., i.e. javax.xml.rpc.Service.
Section 7
The Spring framework provides factory classes based on the following abstract
classes that you use to develop Spring-enabled EJBs.
https://dzone.com/asset/download/10 15/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
To use a Spring factory class to access a Spring bean, your EJB 3 bean class must
implement the onEjbCreate() method.
1 @Stateless(name = "PlaceBid")
2 public class PlaceBidBean extends AbstractStatelessSessionBean
3 implements PlaceBid {
4 private BidServiceBean bidService;
5 public PlaceBidBean() {
6 }
7 protected void onEjbCreate() {
8 bidService =
9 (BidServiceBean) getBeanFactory().getBean("bidService");
0 }
1 public Long addBid(String userId, Long itemId, Double bidPrice) {
2 return bidService.addBid(userId, itemId, bidPrice);
3 }
4
When an EJB instance is created (when a client invokes an EJB), the onEjbCreate
method is invoked automatically. A JNDI lookup is performed to obtain the path for
the bean factory by using an environment entry named ejb/BeanFactoryPath. So you
have to define it in the EJB deployment descriptor for the EJB:
1 <session>
2 <display-name>PlaceBid</display-name>
3 <ejb-name>PlaceBid</ejb-name>
4 <env-entry>
5 <env-entry-name>ejb/BeanFactoryPath</env-entry-name>
6 <env-entry-type>java.lang.String</env-entry-type>
7 <env-entry-value>/actionBazaar-service.xml</env-entry-value>
8 </env-entry>
9 </session>
0
https://dzone.com/asset/download/10 16/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
Although EJB 3 made deployment descriptor optional there are 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 variable at /actionBazaar-service.xml. So you have
to package the EJB classes, Spring classes, and Spring configuration file into your ejb-
jar package. The Spring bean factory (configuration file) defines the Spring beans.
Refer to the Spring Configuration Refcard for details about Spring configuration.
DZone Article
An Introduction To JBoss RichFaces
ABOUT US
About DZone
Send feedback
Careers
Sitemap
ADVERTISE
Advertise with DZone
CONTRIBUTE ON DZONE
Article Submission Guidelines
MVB Program
Become a Contributor
https://dzone.com/asset/download/10 17/18
06/02/2022 12:20 Dependency Injection in EJB 3 - DZone Refcardz
LEGAL
Terms of Service
Privacy Policy
CONTACT US
600 Park Offices Drive
Suite 300
Durham, NC 27709
[email protected]
+1 (919) 678-0300
Let's be friends:
AnswerHub logo
https://dzone.com/asset/download/10 18/18