问答详情
源自:3-1 Spring Bean装配之Bean的配置项及作用域

UnitTestBase.java代码是怎样的?

大神给个代码呗,方便学习

提问者:小小阳 2015-03-24 13:44

个回答

  • moocer
    2015-03-27 11:58:20

    在com.imooc.test.base包下

  • 水木星火
    2017-03-20 15:08:15

    package com.test;

    import org.junit.After;
    import org.junit.Before;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class UnitTestBase {
     private ClassPathXmlApplicationContext context;
     private String stringXmlPath;
     public UnitTestBase() {};
     public UnitTestBase(String stringXmlPath) {
      this.stringXmlPath = stringXmlPath;
     };
     @Before
     public void before(){
      
      if(stringXmlPath==null||stringXmlPath.equals("")){
       stringXmlPath = "classPath*:spring-*.xml";
      }
      try{
       context = new ClassPathXmlApplicationContext(stringXmlPath.split("[,\\s]+"));
       context.start();
      }catch(Exception e){
       e.printStackTrace();
      }
     }
     @After
     public void after(){
      context.destroy();
      
     }
     
     @SuppressWarnings("unchecked")
     protected <T extends Object>T getBean(String beanId){
      return (T)context.getBean(beanId);
     }
     
     protected <T extends Object>T getBean(Class<T> clazz){
      return (T)context.getBean(clazz);
     }

    }