原型模式(prototype)和单例模式(默认情况下)

来源:互联网 发布:python 视频 上传 编辑:程序博客网 时间:2024/05/16 17:32

1. 新建ExampleBean,该类在工程中的位置如图:


        

ExampleBean的代码如下:


package org.spring.dao;public class ExampleBean {/** * 模拟实例化 */public ExampleBean() {System.out.println("实例化ExampleBean");}}
                                                            

2. 在applicationContext.xml文件中,配置ExampleBean。

单例模式的:

<!-- 单例模式 --><bean id="exampleBean" class="org.spring.dao.ExampleBean" scope="singleton" />

原型模式的:

<!-- 原型模式 --><!--<bean id="exampleBean" class="org.spring.dao.ExampleBean" scope="prototype" /> -->


3. 在TestCase中新建测试方法testExampleBean(),在方法中从Spring中获取两个ExampleBean类型对象,通过比较操作符“ == ” 进行比较,如果输出结果为true,则表明两次获取的是同一个对象,即创建对象的方式单例模式。

testCase的代码如下:


package org.spring.test;import org.junit.Test;import org.spring.dao.ExampleBean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class testCase {/** * 测试Spring环境 */@Testpublic void testConfig() {String config = "applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(config);System.out.println(ac);}/** * 单例模式 */@Testpublic void SingletonExampleBean() {// 实例化Spring容器示例String conf = "applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(conf);// 获取ExampleBean对象 ,分別是bean1,bean2ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class);ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class);/*  * 通过比较操作符“ == ” 进行比较,如果输出结果为true, * 则表明两次获取的是同一个对象,即创建对象的方式单例模式。 */System.out.println(bean1 == bean2);// 关闭Spring容器, 注意AbstractApplicationContext类型定义了 close()方法AbstractApplicationContext ctx = (AbstractApplicationContext) ac;ctx.close();}}


4. 运行testExampleBean()方法,控制台输出结果如下:


实例化ExampleBean
true



5. 修改applicationContext.xml,设置创建Bean的模式为原型模式(prototype)

注意要把单例的先屏蔽掉。


6. 再次运行testExampleBean()方法,控制台输出结果如下:


实例化ExampleBean
实例化ExampleBean
false


这个结果说明调用了2次ExampleBean类的构造方法创建了两个Bean对象,比较结果是false表示bean1和bean2引用了这两个不同的对象, 这样创建bean就不再是单例模式了。



0 0
原创粉丝点击