开发者

Customize BeanFactory with SpringJUnit4ClassRunner?

The slow autowire by type problem has finally been solved by creating a caching bean factory.

I would really like to be able to use such a CachingByTypeBeanFactory together with SpringJUnit4ClassRunner for running JUnit tests 开发者_如何学Pythonwith @Autowired. But it does not seem to be possible to change the Bean Factory on the application context via the ContextLoader.

Is there any other way to do this ?


Create your own ContextLoader and attach this annotation to your JUnit class:

@ContextConfiguration(loader=YourLoader.class)

This is my example Loader which instantiates another or custom ApplicationContext which in turn may be initialized with custom BeanFactory (depending of capabilities):

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

}

In above case application context (provided by Spring Framework) has constructor:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜