Java Reference
In-Depth Information
Solution
In Spring 2.0 and later, a bean's scope is set in the scope attribute of the <bean> element. By default,
Spring creates exactly one instance for each bean declared in the IoC container, and this instance will
be shared in the scope of the entire IoC container. This unique bean instance will be returned for all
subsequent getBean() calls and bean references. This scope is called singleton , which is the default
scope of all beans. Table 1-2 lists all valid bean scopes in Spring.
Table 1-2. Valid Bean Scopes in Spring
Scope
Description
singleton
Creates a single bean instance per Spring IoC container
prototype
Creates a new bean instance each time when requested
request
Creates a single bean instance per HTTP request; valid only in the context of a web
application
session
Creates a single bean instance per HTTP session; valid only in the context of a web
application
globalSession
Creates a single bean instance per global HTTP session; valid only in the context of a
portal application
How It Works
To demonstrate the concept of bean scope, consider a shopping cart example in your shop application.
First, you create the ShoppingCart class as follows:
package com.apress.springenterpriserecipes.shop;
...
public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();
public void addItem(Product item) {
items.add(item);
}
public List<Product> getItems() {
return items;
}
}
Search WWH ::




Custom Search