spring-context is a Spring Framework module used to work with the application context. The context is a place in application memory where Spring manages selected object instances. An object in the context is called a bean; objects created outside it are not automatically known to Spring. section 2.0 section 2.1
The context acts as an inversion-of-control container: Spring manages beans so framework features can work with them. Not every application object needs to be a bean—add the ones Spring needs to manage. section 2.1 section 2.5
Create and retrieve a bean
Add the Maven dependency org.springframework:spring-context. In a @Configuration class, define a method annotated with @Bean that creates and returns a Parrot. Start an AnnotationConfigApplicationContext with the configuration class, then call getBean(Parrot.class) to retrieve it. section 2.1
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
}
}This configuration method creates the Parrot that Spring adds to the context. section 2.1
Choose how to add beans according to the task:
- Use @Bean for explicit control over creation, including when you cannot change a third-party class. section 2.5 section 3.1
- Use a stereotype annotation such as @Component for application classes when less boilerplate is useful. section 2.5
- Use registerBean() to add a bean programmatically. section 2.5
When several beans have the same type, a type-only lookup is ambiguous. Use a bean name or designate a primary bean with @Primary to help Spring choose. section 2.1 section 2.5
Link two beans
A Person bean and a Parrot bean do not acquire a relationship just because both are in the context. In a configuration class, the person() method can call parrot() and set the result on the Person. In this example Spring returns the existing Parrot bean if available, or creates it if it does not yet exist. section 3.1 section 3.1.1
