项目结构
新建spring-scope 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="student" class="com.red.spring.pojo.Student">
<property name="sid" value="1001"></property>
<property name="sname" value="张三"></property>
</bean>
</beans>
新建ScopeTest测试类
public class ScopeTest {
@Test
public void testScope(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
Student student1 = ioc.getBean(Student.class);
Student student2 = ioc.getBean(Student.class);
System.out.println(student1 == student2);
}
}
结果为true
下面介绍scope属性
bean添加scope属性,如果是scope="singleton"
结果依然为true
如果scope="prototype"
<!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建 对象 -->
<!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
<bean id="student" class="com.red.spring.pojo.Student" scope="prototype">
<property name="sid" value="1001"></property>
<property name="sname" value="张三"></property>
</bean>
运行结果就会变成false