The IoC container and beans

Spring Boot · lesson 4 of 39 · 3 min read

Know what a bean is, who creates it, and the two ways to register one.

Open this lesson in the learning hub

Key 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 new and instead declares what it needs.
  • Two ways to register: annotate the class (@Component and friends) or return it from an @Bean method.
  • Use @Bean for types you do not own — a third-party client, an ObjectMapper, a Clock.
  • 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.