您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
07-Spring配置文件-详解1(scope的singleton与prototype)
发布时间:2024-12-17 19:10:15编辑:雪饮阅读()
-
上篇中有了解到默认Spring Config配置文件中bean标签的id和class属性,那么除了这两个属性,这次了解下scope属性。
没有声明scope属性时候,默认就是scope属性值为singleton,scope常见有singleton和prototype两个值。
singleton即是单例,也就是从dao的实现容器中取出的时候无论取几次都是取的同一个实例。
而prototype则不同,相当于多实例。
那么如我的applicationContext.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="userDao0" class="com.dao.impl.UserDaoImpl"></bean>
<bean id="userDao" class="com.dao.impl.UserDaoImpl" scope="singleton"></bean>
<bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype"></bean>
</beans>
然后在src下建立test/java下面建立一个Test测试类如:
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void test1(){
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("singleton instance compare:"+(app.getBean("userDao0")==app.getBean("userDao0")));
System.out.println("singleton instance compare:"+(app.getBean("userDao")==app.getBean("userDao")));
System.out.println("prototype instance compare:"+(app.getBean("userDao2")==app.getBean("userDao2")));
}
}
运行该测试,从测试结果如:
singleton instance compare:true
singleton instance compare:true
prototype instance compare:false
就能验证上述。
singleton 单例模式
prototype 原型模式
关键字词:scope,singleton,prototype