AI Hints
Home›Spring Boot Tutorial›@Configuration and @Bean, Bean Scopes and Practice: Layers
Spring Boot · Lesson 34 of 120

@Configuration and @Bean

Beans from methods.

⏱ 2 min read▶ Video at 44:37🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

We can't put at Component on classes we didn't write, like Java's own Clock class. For those, we create beans with a method instead.

  • Classes we didn't write
  • Can't add @Component
  • Use a method

How it works

At Configuration marks a class that holds bean methods. Each method marked at Bean, returns a new bean. Spring calls the method once, and keeps the result in the container. The bean's name is the method's name.

keyvalue
@Configurationa class of bean methods
@Beanthis method makes a bean
Calledonce, by Spring
Namethe method name

ShopConfig.java

Shop config is a configuration class. The first bean is a clock, fixed at half past nine. A fixed clock is handy, because the time never changes in our examples. The second bean is a number format, for British prices.

ShopConfig.javajava
@Configuration
public class ShopConfig {

    @Bean
    public Clock shopClock() {
        return Clock.fixed(Instant.parse("2026-01-05T09:30:00Z"), ZoneOffset.UTC);
    }

    @Bean
    public NumberFormat priceFormat() {
        return NumberFormat.getCurrencyInstance(Locale.UK);
    }
}

Using the beans

The controller asks for a Clock, and a Number Format, in its constructor. Spring finds the beans made by our methods, by their type. The endpoint shows the time, and a formatted price. Run it. The time is half past nine, from our fixed clock. And the price is formatted in pounds.

ShopController.javajava
@RestController
public class ShopController {

    private final Clock clock;
    private final NumberFormat format;

    public ShopController(Clock clock, NumberFormat format) {
        this.clock = clock;
        this.format = format;
    }

    @GetMapping("/status")
    public String status() {
        return "Time: " + LocalTime.now(clock) + "\nDune costs " + format.format(9.99);
    }
}
Output
Time: 09:30
Dune costs £9.99
Also uses ShopConfig.java
@Configuration
public class ShopConfig {

    @Bean
    public Clock shopClock() {
        return Clock.fixed(Instant.parse("2026-01-05T09:30:00Z"), ZoneOffset.UTC);
    }

    @Bean
    public NumberFormat priceFormat() {
        return NumberFormat.getCurrencyInstance(Locale.UK);
    }
}
Also uses _curl.sh
curl localhost:8080/status

Summary

At Configuration classes hold at Bean methods, which create beans for classes you didn't write. Next, bean scopes.

Key takeaways
  • @Configuration
  • @Bean methods
  • Inject by type
Next up: Bean Scopes — one or many