我是 Spring 和 Maven 的新手。最近我构建了spring MVC项目并使用maven来管理项目结构和依赖关系。
当我编写单元测试时,我遇到了一个问题,即我无法从“src/main/java”中获取 bean,并且似乎上下文只从“src/test/java”中加载 bean。
这是我的代码。
单元测试:src/test/java/com/web/component/form
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:META-INF/spring/applicationContext-web-test.xml"})
public class FormTest {
@Autowired
private BeanFactory beanFactory; // I override this bean by myself
}
配置 XML 文件:src/test/resources/META-INF/spring/applicationContext-web-test.xml 这里下面的组件扫描似乎只扫描 src/test/java 中定义的 bean,而不是 src/main/java。
<context:component-scan base-package="com.web">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
覆盖 BeanFactory 类位于 src/main/java/com/web/helper/ 中。
错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.web.helper.BeanFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 41 more
所以,我想问一下,有没有办法改变组件扫描,让它在spring maven单元测试中扫描src/main/java中定义的bean/classes而不是src/test/java?