Scope is the Scope of a Spring Bean. You can declare the Scope of the Bean with the Scope attribute when creating the Bean
The Scope of the type
Spring initially provides two types of Scope
- singleton
- prototype
Since the release of 2.0, however, three more scopes have been introduced:
- request
- session
- global session
These three are only available in Web applications
singleton
Singleton is the default Scope for Spring beans! The Spring IoC container creates only one instance of the same Bean, and caches that instance in the Spring IoC container. If needed, the instance is not created and retrieved directly from the IoC container.
Under the Singleton scope, all beans that depend on this object share the instance, which is the form of the singleton pattern in the design pattern.
Usage scenario: The Singleton scope is recommended for stateless Spring beans
prototype
Each time a Bean is fetched, a new instance is created
Use scenarios: Stateful Spring beans are the only ones that would consider using the Prototype scope
request
Each HTTP request creates its own bean instance, meaning that only one instance of the same bean is created per request scope
session
In an HTTP session, one bean corresponds to one instance, meaning that only one instance of the same bean is created per session scope
global session
In a global HTTP session, one bean corresponds to one instance
However, the Global Session only makes sense in a portlet’s Web application. It maps to the portlet’s Global-scoped session. If a normal Web application uses this scope, The container will treat this as a normal session scope
Method of use
Singleton is the default value of Scope, so how to specify a prototype-scoped Bean
For example, set the scope of the BService dependency to Prototype
@Controller public class AController { private BService b; @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Resource public void setB(BService b) { this.b = b; }}Copy the code
The @scope annotation applies only to non-constructors and classes
Instantiation timing
Singleton-scoped beans are instantiated after the container is started or can be deferred until use via the @lazy annotation
Beans that are not singleton scoped are not instantiated until the Bean is used