有没有办法在运行时获取Spring管理的所有现有会话bean?为当前用户获取它们很容易。
有什么建议吗?
谢谢, XLR
答案 0 :(得分:1)
我不做Spring,但在普通的JSF / JSP / Servlet中你会抓住HttpSessionBindingListener
。基本上,您需要为会话范围bean提供static List<Bean>
属性,并相应地实现接口,以便更新static
和valueBound()
方法中的valueUnbound()
列表。
您可以在this answer中找到详细的代码示例。
答案 1 :(得分:0)
这是我提出的利用Spring的解决方案:
我创建一个名为SessionBeanHolder的普通Spring单例bean。 这个bean包含我的会话bean列表。 当用户登录时,我将会话bean添加到我的SessionBeanHolder。
在Spring中引用会话bean时,实际上是指代理。 因此,使这项工作的关键是获取底层bean以添加到SessionBeanHolder。
以下是示例代码:
注意:我的会话bean称为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;
}
}
}
当然,无论何时想要添加会话bean或获取所有bean的列表,只需自动装配SessionBeanHolder并使用其方法。
@Autowired
SessionBeanHolder sessionBeanHolder;