Monday, January 15, 2007

EJB3 and dependency injection

Mistakes are a way to learn if one has enough persistence to find the solution.
Recently, in my adventure with the EJB3 I learn bit more.

Suposse you have a session bean named A_Bean. Inside it you can use anotations like @Resource, @PersistenceContext, ...
Suposse you have another bean named B_Bean needed by A_Bean in some method. Also B_Bean can have it own @Resource and @PersistenceContext annotations.

To do that, you have to options:

  1. Create the B_Bean by your hand,
  2. Left the container create a B_Bean instance and inject it in your code.
Lets analize the first case with the next code:
@Stateless
public class A_BeanImpl implements A_Bean {

@PersistenceContext
private EntityManager em;

private B_Bean bbean;

public void foo() {
bbean = new B_BeanImlp();
bbena.foo();
}
}
@Stateless
public class B_BeanImpl implements B_Bean {

@PersistenceContext
private EntityManager em;

public void foo() {
// Do something
}
}

Here, when the container instantiates an instance of our A_Bean, it is responsible to obtain a reference to an EntityManager and inject it.
Later in the A_Bean.foo() methos we are creating by our hand an instance of B_Bean. This means the container hadn't had nothing to do with the instanciation and then, the B_Bean EntityManager reference is null, NULL !!!

The second method, let the container create the B_Bean instance is something like:
@Stateless
public class A_BeanImpl implements A_Bean {

@PersistenceContext
private EntityManager em;

@EJB
private B_Bean bbean;

public void foo() {
bbena.foo();
}
}
@Stateless
public class B_BeanImpl implements B_Bean {

@PersistenceContext
private EntityManager em;

public void foo() {
// Do something
}
}
Here, in the A_Bean.foo() method you can invoque a B_Bean method because the container was responsible to instantiate a B_Bean bean and inject it. Also, and the most important, the container has injected the EntityManager references into the B_Bean and they aren't null.

No comments: