2 java spring spring-mvc spring-session
我是Spring MVC的新手,我对bean 的会话范围有疑问.
进入一个项目我有一个Cartbean,这个:
@Component
@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Cart {
private Map<Product, Integer> contents = new HashMap<>();
public Map<Product, Integer> getContents() {
return contents;
}
public Set<Product> getProducts() {
return contents.keySet();
}
public void addProduct(Product product, int count) {
if (contents.containsKey(product)) {
contents.put(product, contents.get(product) + count);
}
else {
contents.put(product, count);
}
}
public void removeProduct(Product product) {
contents.remove(product);
}
public void clearCart() {
contents.clear();
}
@Override
public String toString() {
return contents.toString();
}
public double getTotalCost() {
double totalCost = 0;
for (Product product : contents.keySet()) {
totalCost += product.getPrice();
}
return totalCost;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,容器会自动将此bean检测为组件,并通过以下方式将其设置为会话bean:
@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
Run Code Online (Sandbox Code Playgroud)
因此,根据我的理解,这意味着它会自动为每个用户会话创建一个bean.
在我的示例中,Cart该类表示购物车,其中记录的用户放置想要购买的商品.这是否意味着Cart每个登录的用户部分都存在一个bean进入HttpSession?所以这个bean进入会话,用户可以从中添加或删除项目.这种解释是正确的还是我错过了什么?
另一个疑问与proxyMode = ScopedProxyMode.TARGET_CLASS属性有关.这到底是什么意思呢?为什么它适用于这个bean?
Sot*_*lis 11
因此,根据我的理解,这意味着它会自动为每个用户会话创建一个bean.
会话bean将按用户创建,但仅在请求时创建.换句话说,如果对于给定的请求,您实际上并不需要该bean,则容器不会为您创建它.从某种意义上说,这是"懒惰".
典型的用途是
@Controller
public class MyController {
@Autowired
private MySessionScopeBean myBean;
// use it in handlers
}
Run Code Online (Sandbox Code Playgroud)
在这里,您将会话范围的bean注入到单例范围bean中.Spring会做的是注入一个代理 bean,在内部,它将能够为MySessionScopeBean每个用户生成一个真实对象并将其存储在HttpSession.
注释属性和值
proxyMode = ScopedProxyMode.TARGET_CLASS
Run Code Online (Sandbox Code Playgroud)
定义了Spring如何代理你的bean.在这种情况下,它将通过保留目标类来代理.它将使用CGLIB来实现此目的.另一种方法是INTERFACESSpring使用JDK代理.这些不保留目标bean的类类型,只保留其接口.
您可以在此处阅读有关代理的更多信息:
这是关于请求范围的相关帖子:
| 归档时间: |
|
| 查看次数: |
9280 次 |
| 最近记录: |