Spring框架(八)—— Junit中的类加载spring配置信息

package org.util.test;

import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
import org.junit.*;

public class UnitTestBase {
    private ClassPathXmlApplicationContext context;
    private String springXmlpath;//就是配置spring的bean容器的路径字符串,通过构造器获得
    
    public UnitTestBase(){}
    
    public UnitTestBase(String springXmlpath){
        this.springXmlpath = springXmlpath;
    }
    
    @Before
    public void before(){
        if(StringUtils.isEmpty(springXmlpath)){
            /**
             * classpath*是当前jar包目录下的所有的jar包下进行的操作,
             * 比如扫描等,classpath只是当前单独一个jar包里的操作。比如在扫描器中,
             * classpath只扫描当前包里的class,classpath*则扫描的是当前包目录下所有的包里的class.
             */
            springXmlpath = "classpath*:spring-*.xml";
        }
        try{
            /**
             * str.split(String regex)作用:根据正则表达式regex,将字符串str,
             * 分割成字符串数组。"[,\\s]+" 是一个正则表达式,\\s表示各种空白符,+表示匹配多个。
             * StringUtils是org.apache.commons.lang下的一个用于操作Java.lang.String的工具类,
             * 使用可能需要手工导入commons-lang-xx.jar
             * 把SpringXmlpath路径拆分开来,
             * 因为springXmlpath路径可能是多个路径的拼接,拆分过之后每个路径下的xml都会被扫描识别
             */
            context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
            context.start();//通过扫描xml文件获取并启动容器
        }catch(BeansException e){
            e.printStackTrace();
        }
    }
    
    @After
    public void after(){
        context.destroy();
    }
    
    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId){
        /**
         * T 这是泛型,在你不确定使用什么类型参数的时候,泛型可以代表任意一种类型参数,比较灵活方便
         */
        return (T)context.getBean(beanId);
    }
    protected <T extends Object> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }
}

 

posted @ 2018-06-21 22:45  北宫乾宇  阅读(719)  评论(0编辑  收藏  举报