spring中Bean的作用域

1:和变量一样,bean也有作用域,spring中我们可以为bean指定作用域:<bean id="" class=""  scope="....">


2:作用域的种类

singleton:单例模式,在spring中只有一个实例,无论多少个Bean引用,始终都会指向同一个对象。这也是spring默认的作用域。

prototype:原型模式,spring容器会为每一个引用创建一个新实例。

request:每一个HTTP请求都会创建一个新的bean,但仅仅在当前的request中有效。

session:每一个HTTP Session都会创建一个新的bean,但仅仅在当前HTTP Session中有效。

global Session:在一个全局的HTTP Session中,容器会创建实例,但仅仅在当前范围有效。


实际开发中,单例和原型用的比较多。



3:演示单例模式作用域


bean定义

public class TopicService 
{
	public void addTopic()
	{
		System.out.println("add topic");
	}
}

xml配置bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       					   http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- 生产任意内容 -->
	<bean id="topServiceID" class="com.canyugan.scope.TopicService"></bean>
	
</beans>

测试单例模式下是否引用的是同一个实例:

@Test
	public  void demo1()
	{ 
		String xmlpath="com/canyugan/scope/beans.xml";
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlpath);
		
		TopicService topicService1=applicationContext.getBean("topServiceID",TopicService.class);
		System.out.println(topicService1);
		TopicService topicService2=applicationContext.getBean("topServiceID",TopicService.class);
		System.out.println(topicService2);
	}

结果如下:

com.canyugan.scope.TopicService@1d3d550b
com.canyugan.scope.TopicService@1d3d550b


由此证明了我们的结论。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值