[这个问题类似于“防止@EnableWebMvc-annotated 类被@ComponentScan 拾取”,只是针对该问题使用了不同的攻击向量,我在Spring 4 中遇到了问题]
由于@ComponentScan 找到了所有@Configuration 实例,它还选择了我的WebMvcConfigurationSupport 扩展,这是我在servlet 环境中想要的。但是在集成测试模式下,我不希望这样,因为它抱怨 ServletContext 不存在。
java.lang.IllegalStateException:无法加载 ApplicationContext
在 org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
在 ...
原因:java.lang.IllegalArgumentException:需要 ServletContext 来配置默认 servlet 处理
在 org.springframework.util.Assert.notNull(Assert.java:112)
在 org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.(DefaultServletHandlerConfigurer.java:54)
在 org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:329)
在 ...
我曾经通过使用 @Configuration 注释而不是让 @ComponentScan 找到它来解决这个问题,我使用 AnnotationConfigWebApplicationContext.register(thatClass) 直接包含它,该代码在集成测试设置期间不运行。
这工作得很好,直到我升级到 Spring 4.0.2,在那里我从 4.0 类 CompositeUriComponentsContributor 获得了一个新异常:
引起:java.lang.IllegalArgumentException:'uriComponentsContributors' 不能为空
在 org.springframework.util.Assert.notNull(Assert.java:112) ~[spring-core-4.0.2.RELEASE.jar:4.0.2.RELEASE]
在 org.springframework.web.method.support.CompositeUriComponentsContributor.(CompositeUriComponentsContributor.java:88) ~[spring-web-4.0.2.RELEASE.jar:4.0.2.RELEASE]
在 org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.mvcUriComponentsContributor(WebMvcConfigurationSupport.java:573) ~[spring-webmvc-4.0.2.RELEASE.jar:4.0.2.RELEASE]
在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_51]
在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_51]
在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_51]
在 java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_51]
在 org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166) ~[spring-beans-4.0.2.RELEASE.jar:4.0.2.RELEASE]
...省略了34个常用框架
所以显然,由于某种原因,现在需要“@Configuration-found”,而不是被注册调用包含。
这是为什么?我怎样才能解决这个问题?我明白我可以将它移出@ComponentScan“路径”,但我想知道会发生什么。