I don't understand what problem @Primary
resolves.
The documentation says:
[@Primary] Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
Example code:
@Configuration
class Configuration {
@Bean
@Primary
MyType bean1() {
return new MyType(1);
}
@Bean
MyType bean2() {
return new MyType(2);
}
}
Example:
I have 2 beans, bean1
and bean2
, both with the type MyType
. bean1
has a @Primary
annotation, so when I autowire an object of type MyType
to some constructor, bean1
will be chosen.
Why is it useful to have two beans of the same type if the primary bean will always be chosen? When and how could I use bean2
which isn't annotated as primary? The example shows that bean2
is redundant and unused.