Search code examples
javajakarta-eeejb

Injecting Multiple EJBs


I have a workflow class where I'm injecting several EJB's at the top of my class using the @EJB tag:

@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class WorkflowBean {

   @EJB
   private BeanOne beanOne;
   @EJB
   private BeanTwo beanTwo;
   @EJB
   private BeanThree beanThree;
   @EJB
   private BeanFour beanFour;
   @EJB
   private BeanFive beanFive;
   @EJB
   private BeanSix beanSix;

Is there a better, more organized way of injecting these at the top of my code, maybe on one line somehow? The code works perfectly fine, but I think I am going to add a few more beans by the time the code is complete and I feel that it is starting to cause my code to look cluttered.


Solution

  • There's nothing inherently wrong with doing it that way, but it can get a bit cluttered.

    If you could identify and group together behaviors based on business behavior, it might reduce the number of @EJB annotations. For instance, if beanOne, beanTwo, and beanThree all relate to user management, you could create a userManagement bean, inject them there, and then only inject the one userManagement bean in your workflow bean. It also might help with self-documentation a bit as well.

    IMHO, your workflow bean should pretty much just be calling other beans that encapsulate the business logic, instead of trying to define it all here.