liveBook · Manning

Primary bean

As explained in Spring Start Here, Second Edition

A primary bean is a Spring bean designated as the default candidate when multiple beans of the same type are available.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Explains type-based ambiguity and demonstrates primary designation with an annotation and a registration customizer.
Examples
Uses multiple Parrot beans, including Miki, and a programmatically registered parrot1 bean.
What it assumes
Introduces ordinary Java objects, the Spring context, and bean creation before demonstrating primary selection.
What you can do after
Operate/configure Spring bean selection using @Primary or setPrimary(true), and request a specific bean by name.
How it connects
Connects primary beans to the Spring context, bean names, @Bean methods, and programmatic bean registration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.