Spring入门学习(Bean的作用域) 第六节

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011171125/article/details/85224550

Spring入门学习 第六节

作用域

  1. 使用bean的scope属性来指定创建的bean的作用域,该属性值默认是单例的singleton
  2. 创建一个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>
    
  3. 创建测试类
    	@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
  4. 指定scope="prototype"时再测试得到测试结果为false
  5. 为Car类中添加一个默认的无参构造方法:
    	public Car(){
    		System.out.println("Car's constructor....");
    	}
    
  6. 在测试类中保留如下,看看初始化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
    

猜你喜欢

转载自blog.csdn.net/u011171125/article/details/85224550