Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 671
mmoossen Avatar asked Apr 12 '13 13:04

mmoossen


1 Answers

Try to skip unnecessary beans:

@ComponentScan(basePackages = { "com.blah" }, excludeFilters = @Filter({UnnecessaryBean1.class, UnnecessaryBean2.class}))
like image 105
Maksym Demidas Avatar answered Nov 16 '22 01:11

Maksym Demidas