【问题标题】:why my spring session scoped bean is shared across sessions?为什么我的春季会话范围 bean 跨会话共享?
【发布时间】:2016-08-05 04:38:39
【问题描述】:

我有一个简单的 pojo UserQuota,其中包含 1 个字段 quota

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public interface UserQuota {
    public int getQuota();
    public void setQuota(int quota);
}

现在,我使用两个不同的浏览器窗口(firefox 和 chrome)以两个不同的用户身份登录我的 Web 应用程序。令我惊讶的是,当我从一个会话设置配额值(使用setQuota)时,新值对另一个会话可用(当调用getQuota 时)。我期待每个用户会话都有自己的 bean 实例;这不就是 Spring 的 session scoped bean 的用途吗?

我一定是错过了什么。会是什么?

编辑:

实现类如下所示:

@Component
public class UserQuotaImpl implements UserQuota {

    private int quota;

    /**
     * @return the quota
     */
    public int getQuota() {
        return quota;
    }

    /**
     * @param quota the quota to set
     */
    public void setQuota(int quota) {
        this.quota = quota;
    }

}

最后是我如何使用会话 bean:

@Component
public class UserQuotaHandler {

    @Autowired
    private UserQuota userQuota;

    public void checkAndUpdateQuota() {
        int quota = userQuota.getQuota();

        // i use my business logic to decide whether the quota needs an update
        if(myBusinessLogic) {
            userQuota.setQuota(someNewValue);
        }
    }

}

我在我的 xml 配置文件中使用context:component-scan。可能需要注意的是,我的大多数其他自动装配 bean 都是单例 bean,它们似乎一直在按预期工作

【问题讨论】:

  • 请展示你如何注入和使用 bean。
  • 我已按要求更新了我的问题
  • 实现类在哪里?您需要使用 @Scope 来注释它,而不是界面,afaik。
  • 我在问题中包含了我的实现类。让我检查一下如果我将 @Scope 注释从接口移动到实现会发生什么。将得到结果
  • 优秀。就是这样。现在我得到了预期的行为。非常感谢。您能否将解决方案发布为答案,以便我接受?另外,如果您可以添加一些解释/参考来说明为什么在注释界面时它不起作用,那将不胜感激

标签: java spring session scope session-scope


【解决方案1】:

在您的情况下,您需要使用会话 @ScopeUserQuotaImpl 注释您的具体 bean 类。

Spring 会忽略具体类的任何超类或超接口上的 @Scope。由于您的类型没有任何明确的 @Scope 注释

@Component
public class UserQuotaImpl implements UserQuota {

Spring 假设您打算将其设为单例 bean。

【讨论】:

  • 这意味着我的请求范围 bean 也有同样的问题!只是会话范围 bean 的问题首先浮出水面
  • @Tanvir 一般来说,不要假设注释是“继承的”。
猜你喜欢
  • 1970-01-01
  • 2018-03-06
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多