4
Recently I migrated from Spring to CDI + EJB, I tried to inject my dependencies directly into the constructor as I did in Spring and as it is supported by 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 requires the creation of a constructor without arguments, making the above code not work until such constructor is created.
After creating the second constructor (no arguments) and executing the application I realized that the application used the constructor with arguments in the injections of this EJB possessing the behavior as I expected.
My question is: if my Ejbs built this way are one day exposed to other systems via lookup/JNDI would use the constructor without arguments or would pass the other constructor by injecting the dependencies?
And also not least: the instant application server in memory, in this case I have two constructors, Ejbs with the injected dependencies and others without the dependencies?
The first case I know yes because the CDI does the management and instantiates according to the demand, but the second case of instantiating Ejbs without the dependencies (using the constructor without arguments) I do not know what is behavior. Mostly because I put one System.out
in the two constructors and the two were called worrying me because there would be unnecessary objects being managed by the server.
You are using JTA transactions (managed by the container) or another resource that requires annotation
@Stateless
? If not, you can simply remove this annotation and when injectingUserService
you can use the annotation@Inject
instead of@EJB
. This way you will be using only CDI injection and is discharged from the non-parametized constructor required by the @EJB annotation.– Caffé
I just found out that if you can use Javaee 7, you can have transactions automatically managed using the annotation
@Transactional
. Your question is very nice (I would also like to understand these two instances you are getting) but the fact is that if you do not use the annotation@EJB
you are free of this behavior... "curious", so to speak.– Caffé