JBoss.org Community Documentation

Chapter 14. Introduction to dependency injection

To facilitate test driven development, the EJB 3.0 specification allows you to use annotations to inject dependencies through annotations on fields or setter methods. Instead of complicated XML ejb-refs or resource refs, you can use the @EJB and @Resource annotations to set the value of a field or to call a setter method within your session bean with anything registered within JNDI. You can use the @EJB annotation to inject EJB references and @Resource to access datasources.

Open up org.jboss.tutorial.injection.bean.ShoppingCartBean. ShoppingCartBean uses the Calculator stateless session EJB to do calculations. The example shows two ways to get access to the Calculator EJB. One is:

			
@EJB
private Calculator calculator;
			
		

When the ShoppingCartBean instance is created, the EJB container will set the calculator field using the jndiName of that particular referenced EJB.

You are not limited to injecting dependencies on fields. You can also use @EJB on a setter method. The below example from ShoppingCartBean uses the @EJB annotation to inject the reference to the Calculator session bean:

			
private Calculator set;

@EJB(beanName="org.jboss.tutorial.injection.bean.CalculatorBean")
public void setCalculator(Calculator c)
{
   set = c;
}

			
		

The @javax.annotation.Resource annotation allows you to inject resources.

		
@Resource(mappedName="DefaultDS")
private javax.sql.DataSource ds;
		
		

Note

In JBoss, whenever the mappedName() attribute is specified (with @Resource, @EJB), JBoss will use that as the GLOBAL jndi name to look it up.

The @Resource annotation is used to inject these singletons as well:

			
@Resource
javax.ejb.SessionContext ctx;

@Resource
javax.ejb.TimerService timer;

@Resource
javax.ejb.UserTransaction ut;

			
		

@EJB and @Resource also create an entry within the JNDI ENC of the bean. So, the above @EJB injection will create an entry for the reference calculator bean under "java:comp/env/ejb/calculator".

Building and Running

From the command prompt, move to the "injection" folder under the Section 1.3, “Set the EJB3_TUTORIAL_HOME”

Ant Users:

Make sure your JBossAS-5.x is running

	
$ ant
$ ant run

run:
     [java] Buying 1 memory stick
     [java] Buying another memory stick
     [java] Buying a laptop
     [java] Print cart:
     [java] 2     Memory stick
     [java] 1     Laptop
     [java] Checkout

     
	
Maven Users: Make sure the AS is not running.
$ mvn clean install -PRunSingleTutorial