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!
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
{
..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With