加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – 如何设置spring上下文:component-scan在单元测试环境中

发布时间:2020-12-16 22:51:50 所属栏目:百科 来源:网络整理
导读:我是春天和Maven的新手.最近我构建了 spring MVC项目并使用maven来管理项目结构和依赖项. 当我编写单元测试时,我遇到了一个问题,即我无法从“src / main / java”获取bean,而且似乎上下文只加载来自“src / test / java”的bean. 这是我的代码. 单元测试:sr
我是春天和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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读