zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring入门程序_06【Bean的作用域——以最常用的singleton和prototype为例】

Spring程序入门 常用 bean 06 作用域 为例
2023-09-27 14:25:39 时间

小结

新的需要记忆理解的就是<bean>中新加的属性吧,比如scope="singleton"scope="prototype"。。。具体看下边的xml文件

目录结构

圈起来的就是
在这里插入图片描述

代码(1)—singleton(单例)

先说singleton的例子,与prototype仅仅差别是在中的属性关键字。。。。

空的类

package com.itheima.scope;
public class Scope  {
}

beans4.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">
 	    <!-- 这里是singleton作用域 -->   
	 <bean id="scope" class="com.itheima.scope.Scope" scope="singleton"/>
	
	<!-- 这里就是prototype作用域
 <bean id="scope" class="com.itheima.scope.Scope" scope="prototype" />-->
</beans>

测试类

package com.itheima.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ScopeTest {
	public static void main(String[] args) {
		// 定义配置文件路径
	String xmlPath = "com/itheima/scope/beans4.xml";
		// 加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		// 输出获得实例
System.out.println(applicationContext.getBean("scope"));

		// System.out.println(applicationContext.getBean("scope"));
	}
}

输出(1)—singleton(单例)

可由看出,两个输出均一样,这说明singleton作用域仅仅 创建了一个Scop类的实例。

【注】这里,上面xml文件中不写scope="singleton"也可以,因为默认就是它。。

在这里插入图片描述

代码(2)—prototype(原型)

与代码(1)区别仅仅如下所示

空的类和上边一样,不再写了。。。。。。。。。。。

beans4.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="scope" class="com.itheima.scope.Scope" scope="singleton"/>  -->
	
	  <bean id="scope" class="com.itheima.scope.Scope" scope="prototype" />
</beans>

测试类

package com.itheima.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ScopeTest {
	public static void main(String[] args) {
		// 定义配置文件路径
	String xmlPath = "com/itheima/scope/beans4.xml";
		// 加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		// 输出获得实例
System.out.println(applicationContext.getBean("scope"));

System.out.println(applicationContext.getBean("scope"));

System.out.println(applicationContext.getBean("scope"));
		// ....................
	}
}

输出(2)—prototype(原型)

【注】为了测试,专门又加了一个输出,可以明显看出,prototype作用域可以创建多个不同实例。。。。

在这里插入图片描述