A Spring context can contain several beans of the same type. If you request one by type alone, Spring needs a way to choose. A primary bean is the default candidate: when no name is specified, Spring selects it from the matching beans. section 2.1 section 2.3
Without a primary bean, requesting a single bean by type when several match can result in a NoUniqueBeanDefinitionException. Alternatively, you can request a particular bean by its name. Define only one bean of a given type as primary. section 2.1
For a bean created with an @Bean method, add @Primary to designate the default. Here, a request for a Parrot by type selects Miki, the bean named parrot2. section 2.1
@Bean
@Primary
Parrot parrot2() {
var p = new Parrot();
p.setName("Miki");
return p;
}The @Primary annotation marks the Parrot returned by parrot2() as the default. section 2.1
You can also set a bean as primary when registering it programmatically. Pass a customizer to registerBean() and call setPrimary(true). section 2.3
context.registerBean("parrot1",
Parrot.class,
parrotSupplier,
bc -> bc.setPrimary(true));The final argument configures the registered parrot1 bean as primary. section 2.3
