为什么我的 spring 会话作用域 bean 在会话之间共享?

why my spring session scoped bean is shared across sessions?

我有一个简单的 pojo UserQuota,里面有 1 个字段 quota:

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

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

我一定是漏了什么。它会是什么?

编辑:

实现 class 如下所示:

@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,它们似乎按预期工作

您需要用会话 @ScopeUserQuotaImpl 注释您的具体 bean class。

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

@Component
public class UserQuotaImpl implements UserQuota {

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