Inject dependencies in the constructor of an EJB can cause modularization and performance problems?

4

I recently migrated from Spring to CDI + EJB, I tried to inject my dependencies directly into the builder just like I did in Spring and how it is supported by the CDI but in an EJB:

@Stateless
public class UserService {

     private UserDao userDao;

     @Inject
     public UserService(UserDao userDao) {
        this.userDao = userDao;
     }
...
}

And I came across the EJB specification that forces you to create a constructor with no arguments, so that the above code does not work until that constructor is created.

After creating the second constructor (without arguments) and running the application I realized that the application used the constructor with arguments in the injections of this EJB having behavior the way I expected.

My question is: would my EJBs built in this way one day be exposed to other systems via lookup / JNDI would they use the constructor without arguments or would they go through the other constructor by injecting the dependencies?

And also no less important: the application server instance in memory, in this case I have two constructors, EJBs with dependencies injected and others without dependencies?

The first case I know is because the CDI does the management and instantiating according to the demand, but the second case of instantiating EJBs without the dependencies (using the constructor without arguments) I do not know to say what is behavior. Mainly because I put System.out on both constructors and the two were called me worrying because there would be unnecessary objects being managed by the server.

    
asked by anonymous 10.01.2015 / 20:55

1 answer

1

Sorry for the delay to answer this question because a few days after my doubt I took this question to a former teacher of mine Caelum that healed these doubts. It is as follows:

To resolve potential problems in injecting smaller-scope objects into larger-scope objects, such as injecting a request-scoped object into a session-scoped object, which would not make sense because the dependency would die before the main object , the CDI works with proxies.

So when an injection is made (@Inject) what is actually injected is an object created by the CDI (a proxy) that inherits from my concrete class that should be injected or that implements the interface in case the injection is of an interface.

So in my case the CDI creates an instance of my EJB with no dependencies to use as a proxy (which is why my EJB without a constructor is called) and injects this proxy where my EJB is requested via @Inject. When a method is called from this proxy, it fetches the original EJB (the one that is created via the constructor that owns the dependencies) and invokes the method of this original EJB.

Thank you to Victor Harada for clarifying this question and so I can answer here too.

    
31.03.2015 / 15:49