有什么方法可以覆盖通过组件扫描发现的bean? [英] Is there any way to override a bean discovered by component scan?

查看:132
本文介绍了有什么方法可以覆盖通过组件扫描发现的bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java配置类,直接通过组件扫描提供fooBean和barBean.

I have a java configuration class providing fooBean directly and barBean by component scan.

@Configuration
@ComponentScan(basePackages = { "com.blah" })
public class Config {

    @Bean
    public FooBean fooBean {
        return new FooBean();
    }
}

,我想在测试用例中重用它,我需要用模拟代替bean:

and i want to reuse it in the test cases and i need to replace the beans with mocks:

@Configuration
@Import(Config.class)
public class TestConfig {

    @Bean
    public FooBean fooBean {
        return new FooBeanMock();
    }

    @Bean
    public BarBean barBean {
        return new BarBeanMock();
    }
}

(在这里重用Config并没有多大意义,但是在现实生活中,我有1000个Bean,而我只需要模拟几个)

(here it does not make much sense to reuse Config, but in real life i have 1000 Beans and i need to mock only a few)

此处fooBean被覆盖,但barBean不被覆盖.

Here fooBean gets overridden, but not barBean.

Skipping loading bean definition for %s: a definition for bean " + "'%s' already exists. This is likely due to an override in XML.

还有一个官方问题: https://jira.springsource.org/browse/SPR-9682

There is also an official issue for it: https://jira.springsource.org/browse/SPR-9682

有人知道有什么解决方法可以覆盖由组件扫描发现的bean吗?

does somebody knows any workaround to override a bean discovered by component scan?

考虑到该bean是遗留代码,不能修改,并且没有依赖项(私有属性+ @Resource).

taking into account that the bean is legacy code and can not be modified and there are NO setters for its dependencies (private attributes + @Resource).

推荐答案

尝试跳过不必要的bean:

Try to skip unnecessary beans:

@ComponentScan(basePackages = { "com.blah" }, excludeFilters = @Filter({UnnecessaryBean1.class, UnnecessaryBean2.class}))

这篇关于有什么方法可以覆盖通过组件扫描发现的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆