您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
08-Spring配置文件-详解2(scope为singleton与prototype时implement的不同构造时机)
发布时间:2024-12-17 23:00:43编辑:雪饮阅读()
-
bean的scope值为singleton的时候,则仅在new ClassPathXmlApplicationContext时候对dao的Implement的实现类进行构造,而ApplicationContext. getBean的时候并不会继续构造。
但弱bean的scope的值为prototype时则ApplicationContext. getBean的时候仍然要构造。
另外这里但弱bean的scope的值为prototype时,我看到老师的new ClassPathXmlApplicationContext时候也没有对dao的Implement的实现类进行构造,但我这里测试时候是都有。
可能是与某些什么版本有关吧。
那么我的Spring Config配置文件则如
<?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="userDao" class="com.dao.impl.UserDaoImpl" scope="singleton"></bean>
<bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype"></bean>
</beans>
哦,我瞬间明白了,应该是加载我这个配置文件的时候发现里面有两个bean,所以才多构建一次的。
我的理解是prototype时候对于同一个class则只创建一次,哪怕id不同,而getBean的时候则是创建多次了。
那么我的这两个测试如:
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");
app.getBean("userDao");
app.getBean("userDao");
}
@Test
public void test2(){
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
app.getBean("userDao2");
app.getBean("userDao2");
}
}
singleton:单例模式
prototype:原型模式
关键字词:scope,singleton,prototype