【发布时间】: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