Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

Overview

...

This example shows how to use the @EJB annotation in a bean class to refer to other beans.

This functionality is often referred as dependency injection, and has been introduced in Java EE 5.

In this particular example, we will create two session stateless beans:

  • DataStore session bean
  • DataReader session bean

The DataReader bean uses the DataStore to retrieve some informations, and we will see how we can, inside the DataReader bean, get a reference to the DataStore bean using the @EJB annotation, thus avoiding the use of the JNDI API.

The source for this example is the "injection-of-ejbs" directory located in the openejb-examples.zip available on the download page.

The Code

In this example we develop two simple session stateless beans (DataReader and DataStore), and show how we can use the @EJB annotation in one of these beans to get the reference to the other session bean

DataStore session bean

Local business interface

...

Bean

...

...

Local business interface

...

Bean

...

Remote business interface

...

DataReader session bean

Local business interface

...

Bean

...

Note the usage of the @EJB annotation on the DataStoreRemote and DataStoreLocal fields. This is the minimum required for EJB ref resolution. If you have two beans that implement the same business interfaces, you'll want to the beanName attribute as follows:

...

Local business interface

Bean

...

...

(The remote business interface is not shown for the sake of brevity).

...

...

Several components in Java EE can use the @EJB annotation

...

, such as:

  • Servlets
  • ServletContextListeners
  • Servlet Filters
  • JSF managed beans
  • EJB interceptors
  • JAX-WS service endpoints

Writing a unit test for the example

Writing an unit test for this example is quite simple. We need just to write a setup method to create and initialize the InitialContext, and then write our test methods

setUp

...

Test

...

Running

Running the example is fairly simple. In the "injection-of-ejbs" directory of the examples zip, just run:$ cd ejb-injection

$ mvn clean install

Which should create output like the following.

...

...