@ -4280,14 +4280,89 @@ any). These types must be 'wired up' explicitly via XML or using a Spring `@Bean
@@ -4280,14 +4280,89 @@ any). These types must be 'wired up' explicitly via XML or using a Spring `@Bean
====
[[beans-autowired-annotation-primary]]
=== Fine-tuning annotation-based autowiring with primary
Because autowiring by type may lead to multiple candidates, it is often necessary to
have more control over the selection process. One way to accomplish this is with
Spring's `@Primary` annotation. `@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.
Let's assume the following configuration that define `firstMovieCatalog` as the _primary_
`MovieCatalog`
[source,java,indent=0]
[subs="verbatim,quotes"]
----
@Configuration
public class MovieConfiguration {
@Bean
**@Primary**
public MovieCatalog firstMovieCatalog() { ... }
@Bean
public MovieCatalog secondMovieCatalog() { ... }
// ...
}
----
With such configuration, `MovieRecommender` will use `firstMovieCatalog`
[source,java,indent=0]
[subs="verbatim,quotes"]
----
public class MovieRecommender {
@Autowired
private MovieCatalog movieCatalog;
// ...
}
----
The corresponding bean definitions appear as follows.