简体   繁体   中英

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 with @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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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