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);
    }
}

 

转载于:https://www.cnblogs.com/myfaith-feng/p/9211290.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值