Calling a producer method with limited CDI session coverage from a dormant EJB bean session

I want to add the current user using @Inject @Current User for all layers (i.e. web layer, EJB layer). For this, I have the following CDI Producer method:

 @Named @SessionScoped public class UserController { @Resource SessionContext sessionContext; @EJB UserDao userDao; @Produces @Current public User getCurrentUser() { String username = sessionContext.getCallerPrincipal().getName(); User user = userDao.findByUsername(username); } } @Qualifier @Target({TYPE, METHOD, PARAMETER, FIELD}) @Retention(RUNTIME) public @interface Current{} 

Now I want to enter the current user into the session without saving the state of the EJB bean as follows:

 @Stateless public class SomeBackendService { @Inject @Current private User user; } 

My question is: the current user object is always re-entered after the session is changed, because session dependencies without a bean are usually entered once during creation, and the bean can be combined and used in different sessions

+7
source share
3 answers

Although I have not tried this exact situation , beans are usually not re-injected in CDI. Instead, a proxy server that knows about its context is entered.

Using this mechanism, you can inject, say, a bean session area in a bean application area. Each application user with a bean scope goes to the same bean and the same proxy, but the proxy server then dynamically resolves calls with it to a different bean for each user.

So, although the @Stateless scope is basically a "application", it is possible that the proxy representing User in your `SomeBackendService 'is still delegating the correct scope version.

ps

If with layers you really mean modules, as in web modules and EJB modules that are part of the EAR, this will be a bit more complicated, since CDI does not always work as expected between modules (especially in JBoss AS). this is due to the ambiguity that the β€œapplication” and, therefore, the scope is within the EAR.

+4
source

By design, your session without a bean should not have a user state, it is unlimited.

If you want your EJB to have states, use @Stateful instead.

+1
source

Yes, for every business method called a container, all dependencies of your SLSB will be re-introduced. Here is the text that guarantees this in the EJB 3.1 specification:

"If dependency injection is used in a bean session, the container enters these links after creating the bean instance and before any business methods are called in the bean instance." - Section 4.3.2

I also had this doubt, and I posted a question explaining this situation here

+1
source

All Articles