liveBook · Manning

Spring bean name

As explained in Spring Start Here, Second Edition

A bean name is an identifier assigned to a Spring-managed bean for selecting or referring to that bean.

A Spring bean name identifies an object registered in the Spring context. With @Bean, the method name becomes the bean name: parrot() registers a bean named "parrot". This is distinct from an attribute on the object, such as the parrot’s name "Koko". section 2.1

Choose among beans of the same type

If the context contains parrot1, parrot2, and parrot3, requesting a Parrot by type alone is ambiguous. Use the name to select one: context.getBean("parrot2", Parrot.class). section 2.1

Listing 2.13 Referring to a bean by its identifier
public class Main {
 
  static void main() {
    var context = new 
      AnnotationConfigApplicationContext(ProjectConfig.class);
    
    Parrot p = context.getBean("parrot2", Parrot.class); #A
    System.out.println(p.getName());
 
  }
}

See a name-based lookup selecting the parrot2 bean from the context. section 2.1

How Spring Start Here, Second Edition covers it

How deep it goes
Defines the default name for an @Bean method and demonstrates name-based retrieval when type-only lookup is ambiguous.
Examples
Uses Parrot beans named parrot1, parrot2, and parrot3, contrasting the bean identifier with the object’s name, Koko.
What it assumes
Assumes familiarity with Java classes and methods while introducing Spring bean registration through configuration.
What you can do after
Apply name-based Spring context lookup to select a bean when multiple beans share its type.
How it connects
Connects bean names to the Spring context, @Bean methods, type-based lookup, and @Primary selection.

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.