目录
Spring 容器在初始化一个 Bean 的实例时,同时会指定该实例的作用域。Spring有6个作用域,最后四种是基于Spring WebMVC生效:
一、singleton
官方说明:(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
描述:该作用域下的Bean在IoC容器中只存在一个实例:获取Bean(即通过applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注入)都是同一个对象。
场景:通常无状态的Bean使用该作用域。无状态表示Bean对象的属性状态不需要更新备注:Spring默认选择该作用域
二、prototype
官方说明:Scopes a single bean definition to any number of object instances.
描述:每次对该作用域下的Bean的请求都会创建新的实例:获取Bean(即通过applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注入)都是新的对象实例。
场景:通常有状态的Bean使用该作用域
三、request
官方说明:Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean
definition. Only valid in the context of a web-aware Spring ApplicationContext.
描述:每次http请求会创建新的Bean实例,类似于prototype 场景:一次http的请求和响应的共享Bean
备注:限定SpringMVC中使用
四、session
官方说明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
描述:在一个http session中,定义一个Bean实例
场景:用户回话的共享Bean, 比如:记录一个用户的登陆信息备注:限定SpringMVC中使用
五、application
官方说明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
描述:在一个http servlet Context中,定义一个Bean实例
场景:Web应用的上下文信息,比如:记录一个应用的共享信息备注:限定SpringMVC中使用
六、websocket
官方说明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
描述:在一个HTTP WebSocket的生命周期中,定义一个Bean实例
场景:WebSocket的每次会话中,保存了一个Map结构的头信息,将用来包裹客户端消息头。第一次初始化后,直到WebSocket结束都是同一个Bean。
使用示例:
定义一个Bean,先通过类上的注解来定义为原型模式:
package org.example.dao;
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
@Repository @Scope("prototype")
public class PrototypeRepository {
}
在org.example.App 获取Bean实例:
//getBean每次获取都会创建一个新的Bean对象
PrototypeRepository prototypeRepository1 = (PrototypeRepository) context.getBean("prototypeRepository");
PrototypeRepository prototypeRepository2 = (PrototypeRepository) context.getBean("prototypeRepository"); System.out.printf("prototypeRepository: %s%n", prototypeRepository1 == prototypeRepository2);
在@Bean注解的方法上也可以使用,以下为loginController中定义的又一个用户对象,可以查看
注入的prototype对象是否为同一个:
@Bean
public User user6(PrototypeRepository p1, PrototypeRepository p2){ System.out.printf("user6: p1=%s, p2=%s, p1==p2: %s%n", p1, p2, p1==p2); return new User();
}