Spring Bean作用域

1. Bean的四种作用域

1.1. singleton 单实例

singleton特点:

  • 在容器创建时,Bean就会被实例化
  • 从容器中取出的总是同一个对象,就是一开始被实例化的那个对象
1
2
3
4
5
6
7
8
@Data
public class Car {
private String name;
private Double price;
public Car() {
System.out.println("Car()构造方法");
}
}
1
2
<!-- scope默认值就是singleton,所以可省略不写 -->
<bean id="car" class="bean.Car" scope="singleton" />
1
2
3
4
5
6
7
8
@Test
public void testIoc() throws Exception {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car1 = (Car) ioc.getBean("car");
Car car2 = (Car) ioc.getBean("car");
// true
System.out.println(car1 == car2);
}

1.2. prototype 多实例

prototype特点:

  • 在容器创建时,不会实例化Bean
  • 从容器中取出时,才会实例化Bean,而且每取一次,就会创建一个新的Bean
1
<bean id="car" class="bean.Car" scope="prototype" />
1
2
3
4
5
6
7
8
@Test
public void testIoc() throws Exception {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car1 = (Car) ioc.getBean("car");
Car car2 = (Car) ioc.getBean("car");
// false
System.out.println(car1 == car2);
}

1.3. request / session / global-session

request:在Web环境下,每一个Http Request会创建一个Bean实例
session:在Web环境下,每一个Http Session会创建一个Bean实例
global-session:作用于集群环境下的session(全局session),如果不是集群环境,相当于session

panchaoxin wechat
关注我的公众号
支持一下