XLR
XLR

Reputation: 11

Get all existing session beans from all users in Spring

Is there a way to get all existing session beans managed by Spring at runtime? Getting them for the current user is easy.

Any suggestions?

Thanks, XLR

Upvotes: 1

Views: 2449

Answers (2)

jasop
jasop

Reputation: 912

Here is a solution I came up with that utilizes Spring:

I make a normal Spring singleton bean called SessionBeanHolder. This bean holds a list of my session beans. When a user logs in, I add the session bean to my SessionBeanHolder.

When referring to session beans in Spring, you are actually referring to proxies. So the key thing to making this work was to fetch the underlying bean to add to the SessionBeanHolder.

Below is the sample code:

Note: My session bean is called SessionInfo.

@Scope(value="singleton")
@Component
public class SessionBeanHolder {

    static Set<SessionInfo> beans;

    public SessionBeanHolder() {
        beans = new HashSet<SessionInfo>();
    }

    public Collection<SessionInfo> getBeans() {
        return beans;
    }

    public void addBean(SessionInfo bean) {
        try {
            this.beans.add(removeProxyFromBean(bean));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Fetch the underlying bean that the proxy refers to
    private SessionInfo removeProxyFromBean(SessionInfo proxiedBean) {
        if (proxiedBean instanceof Advised) {
            try {
                return (SessionInfo) ((Advised) proxiedBean).getTargetSource().getTarget();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return proxiedBean;
        }
    }
}

Naturally, whenever you want to add session bean or fetch a list of all beans, just autowire the SessionBeanHolder and use its methods.

    @Autowired
    SessionBeanHolder sessionBeanHolder;

Upvotes: 0

BalusC
BalusC

Reputation: 1108642

I don't do Spring, but in normal JSF/JSP/Servlet you would grab HttpSessionBindingListener for this. Basically you need to give the session scoped bean a static List<Bean> property and implement the interface accordingly that it updates the static list in the valueBound() and valueUnbound() methods.

You can find a detailed code example in this answer.

Upvotes: 1

Related Questions