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

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环境
	 */
	@Test
	public void testConfig() {

		String config = "applicationContext.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(config);
		System.out.println(ac);
	}

	/**
	 * 单例模式
	 */

	@Test
	public void SingletonExampleBean() {

		// 实例化Spring容器示例
		String conf = "applicationContext.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(conf);

		// 获取ExampleBean对象 ,分別是bean1,bean2
		ExampleBean 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就不再是单例模式了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值