spring-210724-09–IOC容器–Bean管理-作用域(设置单&多实例)
scope概念
在Spring 中配置文件bean标签里面有一个属性(scope)用于设置单实例,还是多实例
scope属性:
singleton:默认值,表示单实例对象
prototype:表示多实例对象
singleton和prototype的区别:
设置singleton:
加载spring配置文件的时候就会创建单实例对象。
设置prototype:
不是在加载spring文件的时候创建对象,而是在调用getBean方法的时候创建多实例对象。
Courses.java
package com.bgy.spring.collectiontype;
// 学科
public class Courses {
private String cname;
public void setCname(String cname) {
this.cname = cname;
}
}
scopebean.xml(设置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">
<!--
单实例
scope="singleton"
-->
<bean id="courses_singleton" class="com.bgy.spring.collectiontype.Courses" scope="singleton"></bean>
<!--
多实例
scope="prototype"
-->
<bean id="courses_prototype" class="com.bgy.spring.collectiontype.Courses" scope="prototype"></bean>
</beans>
TestScope.java
import com.bgy.spring.collectiontype.Courses;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
/**
* 测试单实例
* singleton
* 两个对象的地址一样
*/
@Test
public void testSingleton01(){
// 1. 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("scopebean.xml");
// 2. 从配置文件创建对象
Courses courses_singleton01 = context.getBean("courses_singleton", Courses.class);
Courses courses_singleton02 = context.getBean("courses_singleton", Courses.class);
System.out.println(courses_singleton01); // com.bgy.spring.collectiontype.Courses@436e852b
System.out.println(courses_singleton02); // com.bgy.spring.collectiontype.Courses@436e852b
}
/**
* 测试多实例
* prototype
* 两个对象的地址不同
*/
@Test
public void testSingleton02(){
// 1. 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("scopebean.xml");
// 2. 从配置文件创建对象
Courses courses_singleton01 = context.getBean("courses_prototype", Courses.class);
Courses courses_singleton02 = context.getBean("courses_prototype", Courses.class);
System.out.println(courses_singleton01); // com.bgy.spring.collectiontype.Courses@436e852b
System.out.println(courses_singleton02); // com.bgy.spring.collectiontype.Courses@32d2fa64
}
}