【问题标题】:Get all existing session beans from all users in Spring从 Spring 中的所有用户那里获取所有现有的会话 bean
【发布时间】:2011-02-15 10:54:50
【问题描述】:

有没有办法让 Spring 在运行时管理所有现有的会话 bean?为当前用户获取它们很容易。

有什么建议吗?

谢谢, 卡侬

【问题讨论】:

    标签: spring jsf javabeans


    【解决方案1】:

    我不使用 Spring,但在普通的 JSF/JSP/Servlet 中,您会为此获取 HttpSessionBindingListener。基本上,您需要为会话范围的 bean 提供 static List<Bean> 属性并相应地实现接口,以更新 valueBound()valueUnbound() 方法中的 static 列表。

    您可以在this answer中找到详细的代码示例。

    【讨论】:

      【解决方案2】:

      这是我想出的一个利用 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多