0

Given the EJB below, will the container be intelligent enough to only create the object that is used?

@Stateless
public class MyBean {

   @EJB
   Clazz1 obj1;

   @EJB
   Clazz2 obj2;

   public void run(int x) {

     if (x == 1)
         obj1.printCode();
     else
         obj2.printCode();

   }
 }
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • 3
    Err, they're both used. Injection of obj1 and obj2 happens when MyBean is constructed. obj1 or obj2 is then called every time run() is called, which can be a lot of times. – JB Nizet Feb 23 '19 at 13:45
  • Assuming that dozens of classes are injected and that the bean is constructed multiple times, is there a design pattern, such as a factory, that can be used to handle this scenario? – ps0604 Feb 23 '19 at 15:24
  • 1
    You're already using a design pattern: dependency injection. It seems you're concerned about performance, but having dozens of objects injected won't cause any performance problem. If you really have dozens of dependencies injected in a single bean, you should really be concerned about design and maintainability. A bean having dozens of different dependencies clearly has far too many responsibilities. – JB Nizet Feb 23 '19 at 15:59

1 Answers1

0

The container will have to resolve all dependencies of the bean (instantiate them first) before instantiating the bean itself.

Now what truly happens when you invoke a method might differ... You are using purely EJB here, there isn't any speck of CDI in your code! @EJB is an EJB annotation for dependency injection and @Stateless is an EJB annotation for a "scope".

If you were to use CDI and had Weld as its implementation (all EE servers apart from tomee) then you would get lazy instantiation for any normal scoped beans. That would mean that you in fact inject an "empty" proxy object and it will only be instantiated upon first access.

Now, what I mean by CDI injection - use @Inject instead of @EJB. You can still have your bean @Stateless, CDI, if it's running in your app, then wraps it with it's own scope. I also said that you need normal scoped beans - that means beans which use proxies. Those are pretty much all CDI scopes except @Dependent. Therefore it's @RequestScoped, @SessionScoped, @ApplicationScoped. The dependencies of your bean would have to have those scopes to achieve lazy init.

Siliarus
  • 6,393
  • 1
  • 14
  • 30