Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize BeanFactory with SpringJUnit4ClassRunner?

Tags:

java

spring

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 ?

like image 893
krosenvold Avatar asked Jan 07 '11 13:01

krosenvold


1 Answers

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);
}
like image 68
gertas Avatar answered Sep 30 '22 12:09

gertas