单元测试之获取Spring下所有Bean
2014-06-06 00:00
148 查看
单元测试中,针对接口的测试是必须的,但是如何非常方便的获取Spring注册的Bean呢?
如果可以获取所有的Bean,这样就可以将这个方法放到基类中,方便后面所有单元测试类的使用,具体实现如下:
这样后面单元测试的类就可以继承自该类来使用,方便快捷。
获取Spring下所有Bean的关键在于首先指定Spring配置文件的路径:
然后通过appContext来获取注入的Bean:
当然这里需要利用JUnit的@Before,在执行前操作获取Bean。
如果可以获取所有的Bean,这样就可以将这个方法放到基类中,方便后面所有单元测试类的使用,具体实现如下:
1 import org.apache.log4j.Logger; 2 import org.junit.AfterClass; 3 import org.junit.Before; 4 import org.junit.BeforeClass; 5 import org.springframework.beans.factory.support.DefaultListableBeanFactory; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 9 public abstract class BaseTest { 10 protected Logger log = Logger.getLogger(this.getClass()); 11 protected static ApplicationContext appContext; 12 13 @BeforeClass 14 public static void setUp() throws Exception { 15 try { 16 long start = System.currentTimeMillis(); 17 System.out.println("正在加载配置文件..."); 18 19 appContext = new ClassPathXmlApplicationContext(new String[]{"spring-config.xml","spring-config-struts.xml"}); 20 21 System.out.println("配置文件加载完毕,耗时:" + (System.currentTimeMillis() - start)); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 } 26 27 public static void main(String[] args) 7fe8 { 28 System.out.println(BaseTest.class.getResource("/")); 29 } 30 31 protected boolean setProtected() { 32 return false; 33 } 34 35 @Before 36 public void autoSetBean() { 37 appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, DefaultListableBeanFactory.AUTOWIRE_BY_NAME, false); 38 } 39 40 @AfterClass 41 public static void tearDown() throws Exception { 42 } 43 }
这样后面单元测试的类就可以继承自该类来使用,方便快捷。
获取Spring下所有Bean的关键在于首先指定Spring配置文件的路径:
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{"spring config path"});
然后通过appContext来获取注入的Bean:
appContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, DefaultListableBeanFactory.AUTOWIRE_BY_NAME, false);
当然这里需要利用JUnit的@Before,在执行前操作获取Bean。
相关文章推荐
- 通过ApplicationContextAware接口获取Spring配置文件中的所有Bean
- Spring启动后获取所有拥有特定注解的Bean实例代码
- 在web应用中获取spring的context,并打印出context中所有bean的id
- Spring 获取 实现某接口的所有实例bean
- 单元测试使用spring注解获取bean
- Spring启动后获取所有拥有特定注解的Bean
- Spring Boot - 获取所有的Bean信息
- 单元测试使用spring注解获取bean
- SpringBean_获取Spring加载的所有bean(实践)
- Struts 2在Action中获取Spring容器中所有Bean实例名称的方法
- Spring中直接获取bean的工具类
- Spring获取Bean的几种方式
- 第一天看Spring。。。汗。。。获取bean的两种方式
- Spring+Servlet整合(如何向Servlet注入属性(转),servlet获取spring容器中的bean)
- 普通Java类获取Spring的bean
- Spring 使用ApplicationContextAware (bean中获取在ApplicationContext的引用)
- Spring获取Bean的几种方式
- Servlet,Webservice中spring 获取Bean方式
- HttpSessionListener中获取Spring中的Bean
- spring中读取xml配置文件、获取bean的几种方式