详述Spring XML文件配置——Bean标签scope属性

一、引入

当在Spring XML文件中Bean标签中的除lazy-init外各个属性均为默认值时,运行如下代码,观察结果

<?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= "userInfo" class="com.jd.vo.UserInfo" lazy-init="true">	
	</bean>
</beans>
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器
		
		Object object = classPathXmlApplicationContext.getBean("userInfo");//执行getBean()方法,创建对象
                System.out.println(object);
		
	}
}

 观察输出结果,可得到,对象在计算机中被分配的地址。

但当我们将object再次赋值时,我们来再次观察,object对象在计算机中被分配的地址:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器并为xml中配置的类创建对象
		Object object = classPathXmlApplicationContext.getBean("userInfo");
		System.out.println(object);
		object = classPathXmlApplicationContext.getBean("userInfo");//给object对象再次赋值
		System.out.println(object);
	}
}

观察运行结果:

 我们发现,先后的地址相同,这就说明,IOC容器的容量只为一个对象,也就是只能为对象分配一个地址。

那当我们修改Bean标签的scope的属性时,观察结果

<?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= "userInfo" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype">/bean>
</beans>

将scope属性的值设置为"prototype",再次运行刚才的代码:

 这次两次地址不同,可见当scope属性值"prototype"时,每次调用getBean()方法,都会创建一个新的对象,即实例。

且scope属性默认为“singleton”,每次调用getBean()方法产生的均为同一对象。

二、scope标签

scope总共有6种值,详细的论述如下:

【Spring源码解读】bean标签中的属性(一)你可能还不够了解的 scope 属性——弗兰克的猫

发布了91 篇原创文章 · 获赞 10 · 访问量 8014

猜你喜欢

转载自blog.csdn.net/Liuxiaoyang1999/article/details/104503892