[这个问题类似于“Preventing a @EnableWebMvc-annotated class from being picked up by @ComponentScan”,只是针对问题的攻击向量不同,我在Spring 4中遇到了问题]
由于@ComponentScan找到所有@Configuration实例,它还会获取我在servlet环境中所需的WebMvcConfigurationSupport扩展。但是在集成测试模式下,我不希望这样,因为它抱怨ServletContext不存在。
java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) at ... Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling at org.springframework.util.Assert.notNull(Assert.java:112) at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.(DefaultServletHandlerConfigurer.java:54) at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:329) at ...
我过去通过@ComponentScan找到@Ffiguration注释来解决这个问题,而不是让它通过使用AnnotationConfigWebApplicationContext.register(thatClass)直接包含它,这是在集成测试设置期间不运行的代码。
这很好用,直到我升级到Spring 4.0.2,在那里我从4.0类CompositeUriComponentsContributor获得一个新的Exception:
Caused by: java.lang.IllegalArgumentException: 'uriComponentsContributors' must not be null at org.springframework.util.Assert.notNull(Assert.java:112) ~[spring-core-4.0.2.RELEASE.jar:4.0.2.RELEASE] at org.springframework.web.method.support.CompositeUriComponentsContributor.(CompositeUriComponentsContributor.java:88) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE] at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.mvcUriComponentsContributor(WebMvcConfigurationSupport.java:573) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_51] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_51] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_51] at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_51] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166) ~[spring-beans-4.0.2.RELEASE.jar:4.0.2.RELEASE] ... 34 common frames omitted
显然,出于某种原因,现在需要“@ Configuration-found”,而不是被寄存器调用包含在内。
为什么?我怎样才能解决这个问题?我知道我可以将它移出@ComponentScan“路径”,但我想知道会发生什么。
答案 0 :(得分:1)
尝试此操作:使用@WebAppConfiguration
注释集成测试类。这将为Spring MVC设置创建一个模拟ServletContext
。