bean的作用域——Spring对bean的管理(二)

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

本章案例基于上节,看不懂的请先看上节——bean的三种初始化方式:
https://blog.csdn.net/qq_34598667/article/details/83246492


Bean的作用域

bean的作用域:当在 Spring 中定义一个 bean 时,你必须声明该 bean 的作用域的选项。
作用域属性:scope
值:
1、singleton:在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,默认值
2、prototype:每次从容器中调用Bean时,都返回一个新的实例.

3、request:每次HTTP请求都会创建一个新的Bean
4、session:同一个HTTP Session共享一个Bean
5、global-session:一般用于Portlet应用环境,全局Session对象,
注:后三种仅限于Web环境(WebApplicationContext容器)
下面我们来测试前两种


singleton

在每个Spring IoC容器中,一个bean定义只有一个对象实例。
以上节案例为基础,我修改spring.xml配置文件如下:

<?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="demo" class="com.oak.junit.day01.Demo"></bean>
</beans>

使用默认作用域singleton
在测试类中测试

	@Test
	public void testScope(){
		//实例化Spring容器
		ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml"); 
		//获取demo
		Demo demo1=ctx.getBean("demo",Demo.class);
		Demo demo2=ctx.getBean("demo",Demo.class);
		System.out.println(demo1==demo2);//true
	}

测试,控制台输出true,说明了默认情况下bean交给Spring容器管理之后,这个bean就是一个单实例(单例模式)的,即每次调用getBean()方法,获取到的都是同一个bean实例。


prototype

现有一个新需求,要求每次调用getBean()都能得到一个新的对象。修改spring.xml配置文件,设置作用域scope=“prototype” ,代码如下:

<?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="demo" class="com.oak.junit.day01.Demo" scope="prototype"></bean>
</beans>

测试类方法不用改,直接测试:
控制台输出false,证实了若bean的作用域置为prototype,那么每次调用getBean()方法从Spring容器获取bean都将是新的对象。


下一章:Spring对bean的管理(三)——bean的生命周期

猜你喜欢

转载自blog.csdn.net/qq_34598667/article/details/83269250