版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011171125/article/details/85224550
Spring入门学习 第六节
作用域
- 使用bean的
scope
属性来指定创建的bean的作用域,该属性值默认是单例的singleton
- 创建一个car的bean,使用的是第四节中创建的
Car
类<bean id="car" class="com.fafa.spring.autowire.Car" scope="singleton"> <property name="brand" value="Audi"></property> <property name="price" value="300000"></property> </bean>
- 创建测试类
测试结果为@Test public void testScope() { ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath*:beans-scope.xml"); Car car = (Car) ctx.getBean("car"); Car car2 = (Car) ctx.getBean("car"); // scope=singleton的时候为true,prototype时为false System.out.println(car == car2); }
true
- 指定
scope="prototype"
时再测试得到测试结果为false
- 为Car类中添加一个默认的无参构造方法:
public Car(){ System.out.println("Car's constructor...."); }
- 在测试类中保留如下,看看初始化IOC容器时发生了什么:
测试结果:@Test public void testScope() { ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath*:beans-scope.xml"); }
在作用域为Car's constructor....
singleton
模式下,容器初始化时调用了Car的无参构造方法创建了Car对象,每次使用对应的bean时都是同一个对象,所以上面比较car和car2是返回结果是true
当scope="prototype"
时,刚才的测试方法不会返回任何结果,只有在获取bean的时候,容器才会创建对应的对象,且二者比较结果返回false
Car's constructor.... Car's constructor.... false