The IoC container and beans
Know what a bean is, who creates it, and the two ways to register one.
Open this lesson in the learning hubKey points
- A bean is just an object whose lifecycle Spring owns: it creates it, wires it, and hands it out.
- Inversion of Control means your class stops calling
newand instead declares what it needs. - Two ways to register: annotate the class (
@Componentand friends) or return it from an@Beanmethod. - Use
@Beanfor types you do not own — a third-party client, anObjectMapper, aClock. - Default scope is singleton: one instance per application context, shared by everyone. Keep beans stateless.
Example
import java.time.Clock;
import java.net.http.HttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// The method name is the bean name; the return type is the bean type.
@Bean
Clock clock() {
return Clock.systemUTC();
}
@Bean
HttpClient httpClient() {
return HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(5))
.build();
}
}
You describe the objects; the container builds them and wires them together.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.