为什么我的春季会话范围bean在会话中共享?

时间:2016-04-13 20:50:06

标签: java spring session scope session-scope

我有一个简单的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实例;是不是春天的会话范围豆是什么?

我必须遗漏一些东西。它会是什么?

编辑:

实现类如下所示:

@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,似乎已经按预期工作了

1 个答案:

答案 0 :(得分:2)

您希望在您的案例中使用会话@ScopeUserQuotaImpl来注释您的具体bean类。

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

@Component
public class UserQuotaImpl implements UserQuota {

Spring假设你打算把它变成一个单独的bean。

相关问题