
我们创建 bean时可根据scope属性定义创建对象的范围。
Spring framework 支持六个范围,其中四个仅使用在 web-aware ApplicationContext。
| Scope | Description |
|---|---|
| singleton | (默认)将单个 bean 定义范围限定为每个 Spring IoC 容器的单个对象实例。 |
| prototype | 将单个 bean 定义范围限定为任意数量的对象实例。 |
| request | 将单个 bean 定义范围限定为单个 HTTP 请求的生命周期。也就是说,每个 HTTP 请求都有自己的 bean 实例,该 bean 实例是在单个 bean 定义的后面创建的。仅在 web-aware Spring 的上下文中有效ApplicationContext。 |
| session | 将单个 bean 定义范围限定为 HTTP 的生命周期Session。仅在 web-aware Spring 的上下文中有效ApplicationContext。 |
| application | 将单个 bean 定义范围限定为ServletContext. 仅在 web-aware Spring 的上下文中有效ApplicationContext。 |
| websocket | 将单个 bean 定义范围限定为WebSocket. 仅在 web-aware Spring 的上下文中有效ApplicationContext。 |
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String age;
}
Step2:实例化容器
Step3:测试
@org.junit.Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
}
singleton
单例模式:scope="singleton"
此取值时表明容器中创建时只存在一个实例,所有引用此bean都是单一实例。
singleton类型的bean定义从容器启动到第一次被请求而实例化开始,只要容器不销毁或退出,该类型的bean的单一实例就会一直存活,典型单例模式,如同servlet在web容器中的生命周期。
User user1 = applicationContext.getBean("user", User.class);
User user2 = applicationContext.getBean("user", User.class);
System.out.println(user1==user2);
//输出 trueprototype
原型模式:scope="prototype"
每次从容器中get的时候,都会产生一个新对象。
对于那些不能共享使用的对象类型,应该将其定义的scope设为prototype。
User user1 = applicationContext.getBean("user", User.class);
User user2 = applicationContext.getBean("user", User.class);
System.out.println(user1==user2);
//输出 false其余
request,session和global session类型只实用于web程序,通常是和XmlWebApplicationContext共同使用。