Spring之bean的作用域

概述

spring的bean有5大作用域,包括:singleton(单例),prototype(多例),request,session,globalSession.我们经常用到的是singleton和prototype,其中singleton是spring的默认作用域,这里重点测试这两个作用域。
在这里插入图片描述

1.默认的singleton作用域和prototype作用域

singleton作用域:在spring ioc容器中仅存在一个Bean实例,Bean以单例方式存在
第一步:建立一个单例类

public class SingletonBean {
	public SingletonBean() {
		System.out.println("SingletonBean 初始化了单例");
	}
}

创建一个多例类:

public class PrototypeBean {
	public PrototypeBean() {
		System.out.println("PrototypeBean 初始化了多例");
	}
}

第二步:定义spring容器,applicationContext.xml

<!-- bean的作用范围,scope:配置作用域范围的,  spring4中bean的范围默认是单例 -->
	<!-- <bean id="singletonBean" class="com.igeek.scope.SingletonBean" scope="singleton"></bean>-->
	<bean id="singletonBean" class="com.igeek.scope.SingletonBean"></bean>
<!--多例-->	
	<bean id="prototypeBean" class="com.igeek.scope.PrototypeBean" scope="prototype"></bean>

第三步:测试代码,创建SpringTest.java

public class SpringTest {
	@Test
	public void test(){
	    //先构建实例化获取spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		//获取2次单例对象,看看多次获取的bean是不是同一个
		//单例:每次从spring容器中获取的对象是同一个对象
		//单例初始化:是在spring容器初始化的时候就初始化了
		SingletonBean s1 = (SingletonBean) ac.getBean("singletonBean");
		SingletonBean s2 = (SingletonBean) ac.getBean("singletonBean");
		System.out.println(s1);
		System.out.println(s2);
		//获取多例的bean
		//多例:每次从spring容器中获取的对象,不是同一个对象
		//多例初始化:是在getBean的时候初始化的,相当于每次getBean就是在new Bean();
		PrototypeBean pb1 = (PrototypeBean) ac.getBean("prototypeBean");
		PrototypeBean pb2 = (PrototypeBean) ac.getBean("prototypeBean");
		System.out.println(pb1);
		System.out.println(pb2);
	}
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值