作用域主要是分为两种,singleton与prototype
Singleton是单例类型
Prototype是原型类型
- Singleton
- 在IOC容器中bean以单例形式存在,bean作用范围的默认值;singletype声明时,在项目启动时,IOC容器就直接创建了一个bean的实例,并且只会创建一次,而且每次获取到的对象都是同一个对象;
作用的格式:
例子:
1、创建一个car类
package com.cmj.beantest;
public class Car {
private String brand;
private int price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Car(String brand, int price) {
super();
this.brand = brand;
this.price = price;
}
public Car() {
super();
// TODO Auto-generated constructor stub
}
// @Override
// public String toString() {
// return "Car [brand=" + brand + ", price=" + price + "]";
// }
}
2、配置对应的bean
3、测试对应作用域,是否都为同一个对象
package com.cmj;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cmj.beantest.Car;
public class BeanTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("BeanTest.xml");
Car car = (Car) ctx.getBean("car");
Car car2 = (Car) ctx.getBean("car");
System.out.println(car);
System.out.println(car2);
}
}
返回值:
我们可以将对应的toString方法关闭,这样可以看到获取到的对象地址,可以发现地址都是同一个,所以可以确认通过singleton修饰的,每个Spring IoC容器只有一个实例,无论创建多少个对象,调用多少次getMessafe( )方法获取它,它总是返回同一个实例。
2、
- prototype:
- 当作用域为prototype时,表示的bean定义的多个对象实例;在项目启动时,不会主动去创建bean的实例,只有当我们获取需要bean的时候,才会去创建一个对象,并且每次都会被获取到一个新的对象
配置对应的bean
测试对应作用域,是否都为不同对象
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("BeanTest.xml");
Car car3 = (Car) ctx.getBean("car2");
Car car4 = (Car) ctx.getBean("car2");
System.out.println(car3);
System.out.println(car4);
}
结果输出:
会发现,两个bean的实例所传输出来的地址是不一致的,可以确认为,他们为两个不一样的对象;也就是说明,通过prototype修饰的,只有在调用这个bean时,才会被创建对象,并且后续创建的对象都是新创建的实例



