How to get all instances of a specific cdi session in bean mode

I have a @SessionScoped cdi bean that is used to track the session information of a user in my web application. Is there a way to find all the objects of this bean from another @ApplicationScoped bean?

+3


source to share


1 answer


You cannot do this out of the box. Java EE disallows this sort of thing for security reasons.

Now you can imagine more sophisticated approaches to keep track of this session beans at the level of your application area. The cleanest way is to create them from a @ApplicationScoped

bean:



@ApplicationScoped
public class Registry {
  private List<SessionData> data = new ArrayList<>;

  @Produces
  @SessionScoped
  public SessionData produceSessionData() {
    SessionData ret = new SessionData();
    data.add(ret);
    return ret;
  }

  public void cleanSessionData(@Disposes SessionData toClean) {
    data.remove(toClean);
  }
}

      

Pay attention to the method @Dispose

that will be called when your created bean has finished its lifecycle. A convenient way to keep your list up to date and avoid additional memory usage.

+2


source







All Articles