Is there any way to override a bean discovered by component scan?

mmoossen picture mmoossen · Apr 12, 2013 · Viewed 11.8k times · Source

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();
    }
}

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();
    }
}

(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)

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.

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

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

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).

Answer

Maksym Demidas picture Maksym Demidas · Apr 12, 2013

Try to skip unnecessary beans:

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