[英]Customize BeanFactory with SpringJUnit4ClassRunner?
The slow autowire by type problem has finally been solved by creating a caching bean factory. 通过创建缓存bean工厂终于解决了类型问题的慢速自动装配问题 。
I would really like to be able to use such a CachingByTypeBeanFactory together with SpringJUnit4ClassRunner for running JUnit tests with @Autowired. 我真的希望能够将这样的CachingByTypeBeanFactory与SpringJUnit4ClassRunner一起用于使用@Autowired运行JUnit测试。 But it does not seem to be possible to change the Bean Factory on the application context via the ContextLoader.
但似乎无法通过ContextLoader在应用程序上下文中更改Bean Factory。
Is there any other way to do this ? 有没有其他方法可以做到这一点?
Create your own ContextLoader and attach this annotation to your JUnit class: 创建自己的ContextLoader并将此批注附加到JUnit类:
@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): 这是我的示例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 "";
}
} }
In above case application context (provided by Spring Framework) has constructor: 在上面的例子中,应用程序上下文(由Spring Framework提供)具有构造函数:
public GenericWebApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.