EJB reinjected all dependencies before each business method call

513 views Asked by At

This question is not a doubt, in truth is a tip.

Did you know that a session EJB reinjected all dependencies before each business method call? Well, I didn't know until few minutes ago and it gave me a big headache.

I thought that the dependency injection occur only in creation of instance, but, it is no truth. Specification of EJB 3.1 says:

"If a session bean makes use of dependency injection, the container injects these references after the bean instance is created, and before any business methods are invoked on the bean instance." Section 4.3.2

Somehow this definition can give the Stateless Session Bean the capacity of have a conversational state, that exactly is what i needed. For example, if you inject in a SLSB a @SessionScoped bean independently of which instance of the pool process your request the SessionScoped bean always will be compliance with session of the current client. In others words, there is no possibility of the SLSB instance to have a SessionScoped bean of another client.

This enables that a SLSB receives a logged user as a instance field through @Inject without causes any problem if two users use same instance of SLSB alternately. For example:

@Stateless
public class StatelessSessionBean{
    @Inject
    @LoggedInUser
    protected User loggedInUser;//@SessionScoped

    public void test(){
        System.out.println("ejb:"+this);
        System.out.println("user:"+this.loggedInUser);
    }
}

Then, the result of various invocations of "test" method is this:

User 1 invoke
17:02:20,800 INFO  [stdout] (http--0.0.0.0-8080-5) ejb:AccessControlBean@406189
17:02:20,801 INFO  [stdout] (http--0.0.0.0-8080-5) user:User 1

User 2 invoke
17:02:56,227 INFO  [stdout] (http--0.0.0.0-8080-8) ejb:AccessControlBean@406189
17:02:56,228 INFO  [stdout] (http--0.0.0.0-8080-8) user:User 2

User 2 invoke
17:03:24,376 INFO  [stdout] (http--0.0.0.0-8080-8) ejb:AccessControlBean@406189
17:03:24,378 INFO  [stdout] (http--0.0.0.0-8080-8) user:User 2

User 1 invoke
17:03:24,517 INFO  [stdout] (http--0.0.0.0-8080-6) ejb:AccessControlBean@1c05227
17:03:24,518 INFO  [stdout] (http--0.0.0.0-8080-6) user:User 1

User 1 invoke
17:04:24,045 INFO  [stdout] (http--0.0.0.0-8080-1) ejb:AccessControlBean@406189
17:04:24,047 INFO  [stdout] (http--0.0.0.0-8080-1) user:User 1

User 2 invoke
17:04:24,179 INFO  [stdout] (http--0.0.0.0-8080-8) ejb:AccessControlBean@1c05227
17:04:24,179 INFO  [stdout] (http--0.0.0.0-8080-8) user:User 2

Note that even calling the same instance the field "loggedInUser" correctly varies according to the user who invoked the method.

0

There are 0 answers