码迷,mamicode.com
首页 > 编程语言 > 详细

Junit中的类加载spring配置信息

时间:2018-06-21 23:48:38      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:imp   就是   war   after   TE   ons   org   pack   cep   

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

Junit中的类加载spring配置信息

标签:imp   就是   war   after   TE   ons   org   pack   cep   

原文地址:https://www.cnblogs.com/myfaith-feng/p/9211290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!