簡體   English   中英

bean的會話范圍如何在Spring MVC應用程序中運行?

[英]How does the session scope of a bean work in a Spring MVC application?

我是Spring MVC的新手,我對bean的會話范圍有疑問。

進入一個項目我有一個Cart bean,這個:

@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;
    }

}

因此,容器會自動將此bean檢測為組件,並通過以下方式將其設置為會話bean

@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)

因此,根據我的理解,這意味着它會自動為每個用戶會話創建一個bean。

在我的示例中, Cart類表示購物車,其中記錄的用戶放置想要購買的物品。 是否意味着每個登錄用戶部分都存在一個Cart bean進入HttpSession 所以這個bean進入會話,用戶可以從中添加或刪除項目。 這種解釋是正確的還是我錯過了什么?

另一個疑問與proxyMode = ScopedProxyMode.TARGET_CLASS屬性有關。 這到底是什么意思呢? 為什么它適用於這個bean?

因此,根據我的理解,這意味着它會自動為每個用戶會話創建一個bean。

會話bean將按用戶創建,但僅在請求時創建。 換句話說,如果對於給定的請求,您實際上並不需要該bean,則容器不會為您創建它。 從某種意義上說,這是“懶惰”。

典型的用途是

@Controller
public class MyController {
    @Autowired
    private MySessionScopeBean myBean;
    // use it in handlers
}

在這里,您將會話范圍的bean注入到單例范圍bean中。 Spring會做的是注入一個代理 bean,在內部,它將能夠為每個用戶生成一個真正的MySessionScopeBean對象並將其存儲在HttpSession

注釋屬性和值

proxyMode = ScopedProxyMode.TARGET_CLASS

定義了Spring如何代理你的bean。 在這種情況下,它將通過保留目標類來代理。 它將使用CGLIB來實現此目的。 另一種選擇是INTERFACES ,其中Spring使用JDK代理。 這些不保留目標bean的類類型,只保留其接口。

您可以在此處閱讀有關代理的更多信息:

這是關於請求范圍的相關帖子:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM