EJB 3: From legacy technology to secret weapon

Four factors that streamline and modernize EJB 3 development

1 2 3 4 5 6 Page 5
Page 5 of 6

Injecting resources

The injection of resources works slightly differently, although the principle is the same. DataSources, JMS resources, or mail Sessions are injected using the @Resource annotation, as shown in Listing 14.

Listing 14. Injecting resources from JNDI

public class DataSourceInjectionBean implements DataSourceInjection {
@Resource(mappedName = "mail/Context")
private Session mailContext;

@Resource(mappedName = "jms/Queue")
private Queue queue;
@Resource(mappedName = "jms/ConnectionFactory")
private ConnectionFactory eocFactory;

private DataSource ds;

public void accessResources(){
//use the datasource


The deployed resources are uniquely identified by the JNDI name, which can be used for injection, instead of "traditional" lookup. You can use the mappedName attribute for this purpose, although it is just a suggestion in the EJB specification and not mandatory behavior.

You can introduce additional indirection with the name attribute (see the DataSource in Listing 14), which can be resolved later in the application server specific deployment descriptor. Especially in this case, remember to "keep it simple." Every indirection costs you additional effort, which can be overwhelming at the end. Just think of all the overconfigured J2EE projects you've seen.

1 2 3 4 5 6 Page 5
Page 5 of 6