CDI Injection in Interceptors
dxmann73 Nov 15, 2013 5:59 AMI've been digging through a lot of articles yesterday, but I'm still not sure: Is CDI injection in Interceptors supposed to work or not?
Maybe I'm on the completely wrong track, but consider the following example:
public class Producers {
@Produces @SessionScoped
public void User getUser() {
return new User(1L);
}
@Produces
public void Subject getSubject() {
return SecurityUtils.getSubject(); // lazy init from Shiro
}
}
@Interceptor // to secure EJB method access
public class SecurityCustomInterceptor {
@Inject User currentUser; // is null, have to user CDI.current().select(User.class); at runtime
@Inject Subject currentSubject; // is not null, but shows some strange behaviour
}
Now, the WELD docs state "Dependency injection always occurs when the bean instance is first instantiated by the container."
Thus, if I use this interceptor on an EJB, the Interceptor instance would be created at the time the EJB instance is created and pooled, right?
So, when the EJB instance is passivated and then activated again for another user/session, the values are not "re-injected" again, right?
The effect that I'm seeing is that on the first login/user Session, the Interceptor works fine. After logout / session.invalidate() the Interceptor seems to "keep" the old subject. Because: When another user tries to log in and the interceptor fires for the first time, the subject is looking for some things cached in the Session, delegating to Undertow. Undertow in turn complains that it can not find a session with this ID - which is the session ID of the user that just logged out, not the current sessionID.
Maybe this is a caching issue with Shiro, but I don't think so.
As I said, I'm not sure how this is supposed to work. I would either forbid injection in an interceptor (Exception on creation time by container) or re-inject every time the bean comes back, especially seeing that the scope of the Producer in question is @Dependent.
What do you think?
Kind regards,
David