Spring Bean的作用域测试

来源:互联网 发布:金蝶erp软件介绍 编辑:程序博客网 时间:2024/06/05 07:30

基础测试类UnitTestBase:
package gdufe.injectionDao.test;import org.junit.After;import org.junit.Before;import org.springframework.beans.BeansException;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.util.StringUtils;public class UnitTestBase {private ClassPathXmlApplicationContext context;private String springXmlpath;public UnitTestBase() {}public UnitTestBase(String springXmlpath) {this.springXmlpath = springXmlpath;}@Beforepublic void before() {if (StringUtils.isEmpty(springXmlpath)) {springXmlpath = "classpath*:spring-*.xml";}try {context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));context.start();} catch (BeansException e) {e.printStackTrace();}}@Afterpublic void after() {context.destroy();}@SuppressWarnings("unchecked")protected <T extends Object> T getBean(String beanId) {try {return (T)context.getBean(beanId);} catch (BeansException e) {e.printStackTrace();return null;}}protected <T extends Object> T getBean(Class<T> clazz) {try {return context.getBean(clazz);} catch (BeansException e) {e.printStackTrace();return null;}}}
BeanScope:
在hashCode()方法中,我们可以根据输出判断是不是同一个类
package gdufe.injection.bean;public class BeanScope {public void say(){System.out.println("结果:"+this.hashCode());}}
测试类:TestBeanScope:
package gdufe.injectionDao.test;import gdufe.injection.bean.BeanScope;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;@RunWith(BlockJUnit4ClassRunner.class)public class TestBeanScope extends UnitTestBase {public TestBeanScope(){super("classpath*:spring-beanscope.xml");}@Testpublic void testSay(){BeanScope beanScope=super.getBean("beanScope");beanScope.say();BeanScope beanScope1=super.getBean("beanScope");beanScope1.say();}}


当scope=“singleton”,spring-bean.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"    xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="beanScope" class="gdufe.injection.bean.BeanScope" scope="singleton">   </bean>                </beans>
输出结果:
结果:1864350231
结果:1864350231 可以看出是同一个类
当scope="prototype"
输出结果:
结果:1668627309
结果:1795799895 不同的类

 


0 0