当前位置 : 主页 > 网页制作 > xml >

xml – 如何设置spring上下文:component-scan在单元测试环境中扫描“src / main / jav

来源:互联网 收集:自由互联 发布时间:2021-06-13
我是春天和Maven的新手.最近我构建了 spring MVC项目并使用maven来管理项目结构和依赖项. 当我编写单元测试时,我遇到了一个问题,即我无法从“src / main / java”获取bean,而且似乎上下文只加
我是春天和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?

要获得BeanFactory,您可以实现BeanFactoryAware
网友评论