Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

EJB 3.0 and Dependency Injection

  Asked By: Lloyd    Date: Dec 18    Category: Java    Views: 2619

Dependency injection is the opposite of jndiContext.lookup(). The idea of dependency injection is that objects and services specify which resources and configuration values they require, and their container automatically injects these values. Dependency injection is supported for any session bean type and will also be supported in the greater J2EE specification in items such as servlets. This approach requires no JNDI lookup at all and can greatly simplify code. Let's look at an example.

public class ShoppingCartBean implements ShoppingCart
@Inject private UserTransaction userTx;
@Inject private EntityManager entityManager;

private Petstore store;

@EJB(name="petstore") public void setPetstore(Petstore store) {
this.store = store;
When an instance of ShoppingCartBean is allocated, the EJB container will look up the UserTransaction service and set the userTx variable. It will also get a reference to the EJB whose ejbName is "petstore" and call the setPetstore() method. Values can be injected either with an explicit field set or by calling a setter method. A great side effect of injection is that it becomes possible to test beans outside the context of a container. @Resource is another annotation for injecting things like DataSources and JMS connections




No Answers Found. Be the First, To Post Answer.

Didn't find what you were looking for? Find more on EJB 3.0 and Dependency Injection Or get search suggestion and latest updates.