Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - @Primary fails against @ComponentScan?

For a simple POJO:

@Component
public class Foo
{
    private final String string;

    public Foo()
    {
        this("Secondary ComponentScan??");
    }

    public Foo(String string)
    {
        this.string = string;
    }

    @Override
    public String toString()
    {
        return string;
    }
}

and this configuration

@Configuration
@ComponentScan(basePackageClasses = Foo.class)
public class TestConfiguration
{
    @Primary
    @Bean
    public Foo foo()
    {
        return new Foo("Primary bean!!");
    }
}

I would expect the following test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfiguration.class)
public class Test
{
    @Autowired
    private Foo foo;

    @Test
    public void test()
    {
        System.out.println(foo);
    }
}

to print out Primary Bean!! but it returns Secondary ComponentScan?? instead...

How come? Nowhere does the documentation for @Primary say it fails against component-scanned beans!

like image 327
ManRow Avatar asked Jul 30 '13 11:07

ManRow


1 Answers

The reason is that both beans actually have the same name foo, so internally one bean definition is getting overridden with the other one, essentially the one with @Bean is getting overridden by the one being scanned by @ComponentScan.

The fix is simply to give one of them a different name and you should see the correct behavior of the @Primary bean getting injected.

@Primary
@Bean
public Foo foo1()
{
    return new Foo("Primary bean!!");
}

OR

@Component("foo1")
public class Foo
{
..
like image 198
Biju Kunjummen Avatar answered Oct 14 '22 10:10

Biju Kunjummen