users@glassfish.java.net

injecting s.bean X into bean A and passing it to bean B - is that valid approach?

From: Witold Szczerba <pljosh.mail_at_gmail.com>
Date: Tue, 13 May 2008 10:19:41 +0200

Hi there,
I have a situation like this: there is just a regular Java class
TxExecutor, but it does requires some SysPropServiceBean (actually it
depends on SysPropServiceLocal) and maybe in the future it would
depend on something else/more. So, when I need TxExecutor somewhere in
my application I have to do it like this:
@Session
public class SomeServiceBean implements SomeServiceLocal {

  @EJB SysPropServiceLocal sysPropServiceBean; //I really do not care
about this service

  public void doSomething() {
    TxExecutor txExecutor = new TxExecutor(sysPropServiceBean);
    //do something with txExecutor
  }
}

It works fine, but it actually forces me to declare dependency on some
service (SysPropService) that I really do not care about. Moreover,
when that dependency change, I would have to refactor many many places
in application (and this is what I will probably have to do, so this
time I would like to do it better). So I was thinking about adding a
method into my TxServiceBean like this:

@Session
public class TxServiceBean implements TxServiceLocal {

  @EJB SysPropServiceLocal sysPropServiceBean;

  public TxExecutor createTxExecutor() {
    return new TxExecutor(sysPropServiceBean);

  }
}


and now, my SomeServiceBean could look like this:
@Session
public class SomeServiceBean implements SomeServiceLocal {

  @EJB TxServiceLocal txServiceBean; //yes, this bean needs
transaction subsystem

  public void doSomething() {
    TxExecutor txExecutor = txServiceBean.createTxExecutor();
    //do something with txExecutor
  }
}

The big change is that I can change and customize TxExecutor creation
in one place and every other service will not notice. Moreover the
code is much more explicit as now my SomeService declares dependency
on Transaction subsystem, not some unrelated services.

The question is: is that technically valid approach? The big
difference is that after that change, the SysPropService is injected
into TxServiceBean, but it will be used (by TxExecutor) in
SomeServiceBean - which means it will be used outside the scope of its
injection. What if SysPropService use EntityManager? Is SessionContext
from SomeServiceBean going to be propagated into TxServiceBean (when
configuring SysPropServiceBean) correctly?

Regards,
Witold Szczerba