繁体   English   中英

使用SpringJUnit4ClassRunner自定义BeanFactory?

[英]Customize BeanFactory with SpringJUnit4ClassRunner?

通过创建缓存bean工厂终于解决了类型问题慢速自动装配问题

我真的希望能够将这样的CachingByTypeBeanFactory与SpringJUnit4ClassRunner一起用于使用@Autowired运行JUnit测试。 但似乎无法通过ContextLoader在应用程序上下文中更改Bean Factory。

有没有其他方法可以做到这一点?

创建自己的ContextLoader并将此批注附加到JUnit类:

@ContextConfiguration(loader=YourLoader.class)

这是我的示例Loader,它实例化另一个或自定义ApplicationContext,而后者又可以使用自定义BeanFactory初始化(取决于功能):

public class XmlWebApplicationContextLoader extends AbstractContextLoader {

    public final ConfigurableApplicationContext loadContext(final String... locations) throws Exception {
        ServletContext servletContext = new MockServletContext("war", new FileSystemResourceLoader());
        GenericWebApplicationContext webContext = new GenericWebApplicationContext();
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
        webContext.setServletContext(servletContext);
        new XmlBeanDefinitionReader(webContext).loadBeanDefinitions(locations);        
        AnnotationConfigUtils.registerAnnotationConfigProcessors(webContext);
        webContext.refresh();
        webContext.registerShutdownHook();
        return webContext;
    }

    protected String getResourceSuffix() {
        return "";
    }

}

在上面的例子中,应用程序上下文(由Spring Framework提供)具有构造函数:

public GenericWebApplicationContext(DefaultListableBeanFactory beanFactory) {
    super(beanFactory);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM