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

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
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值