liveBook · Manning

Configuration class

As explained in Spring Start Here, Second Edition

A configuration class is a Spring class annotated with @Configuration that declares instructions for configuring the Spring context.

Spring can manage an object only when it is part of the Spring context. A configuration class, marked with @Configuration, gives Spring instructions for setting up that context, including which objects to add as beans. section 2.1

To add a bean explicitly, define an @Bean method in the configuration class. The method creates and returns the object; Spring adds the returned instance to its context. Initialize the context with the configuration class, for example using new AnnotationConfigApplicationContext(ProjectConfig.class). section 2.1 section 2.2

Listing 2.6 Defining the @Bean method
@Configuration
public class ProjectConfig {
 
  @Bean   #A
  Parrot parrot() {
    var p = new Parrot();
    p.setName("Koko");   #B
    return p;   #C
  }
}

ProjectConfig declares a Parrot bean: the method creates the parrot, sets its name, and returns it for Spring to manage. section 2.1

A configuration class can declare several beans, including multiple instances of the same type. If a type-only lookup finds several matches, it is ambiguous; request a bean by its identifier or designate a primary bean. section 2.1

A configuration class can also direct component scanning. Mark a class with @Component, then use @ComponentScan on the configuration class to tell Spring where to find it. This approach needs no @Bean method for that component, and it can be combined with explicit @Bean methods. section 2.2

Connecting beans

A Person and a Parrot can both be beans without being connected: the person's parrot is initially null. To establish the relationship, use wiring by calling a bean method or use Spring's dependency injection through autowiring. section 3.1

How Spring Start Here, Second Edition covers it

How deep it goes
Works through bean creation, context initialization, multiple-bean selection, component scanning, and relationships between beans.
Examples
Uses a named Parrot bean, multiple parrots, and a Person–Parrot relationship to illustrate configuration.
What you can do after
Apply it via Spring to declare beans, configure component scanning, and establish bean relationships.
How it connects
Connects Spring context configuration with beans, component scanning, wiring, autowiring, and dependency injection.

Also explained in

Compare how 3 books explain configuration class →

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.