public class UnitTestBase {
private ClassPathXmlApplicationContext context;
private String springXmlpath;//spring的xml文件路径
public UnitTestBase() {}
public UnitTestBase(String springXmlpath) {
this.springXmlpath = springXmlpath;
}
//在Test方法执行前执行
@Before
public void before(){
if(StringUtils.isEmpty(springXmlpath)){
springXmlpath = "classpath*:spring-*.xml";
}
try{
//spring容器
context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));
//split()切割掉所有,逗号 任何空白字符 +匹配前面表达式一次或多次
context.start();
}catch(Exception ex){
ex.printStackTrace();
}
}
//在Test方法执行后执行
@After
public void after(){
context.destroy();//销毁
}
@SuppressWarnings("unchecked")//忽略unchecked警告信息
protected <T extends Object> T getBean(String beanId){
try {
return (T)context.getBean(beanId);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
protected <T extends Object> T getBean(Class<T> clazz){
try {
return (T)context.getBean(clazz);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
}
@Scope("prototype")
@Component
public class BeanAnnotation {
public void say(String str){
System.out.println("BeanAnnotation:"+str);
}
public void myHashCode(){
System.out.println("BeanAnnotation:"+this.hashCode());
}
}
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase{
public TestBeanAnnotation(){
super("classpath*:spring-beanannotation.xml");
//super("classpath*:spring-beanannotation.xml");
}@Testpublic void testSay(){BeanAnnotation bean = super.getBean("beanAnnotation");bean.say("this is test.");}@Testpublic void testScope(){//测试Scope()注解的作用域prototype,每次有请求的时候,都会创建一个对象BeanAnnotation bean = super.getBean("beanAnnotation");bean.myHashCode();bean = super.getBean("beanAnnotation");bean.myHashCode();}}
Spring可以通过指定classpath*:与classpath:前缀加路径的方式从classpath加载文件,如bean的定义文件classpath*:的出现是为了从多个jar文件中加载相同的文件classpath:只能加载找到的第一个文件.