Skip to lesson

@Configuration and @Bean

Some objects ShopLite needs, such as the JDK's Clock, are classes we did not write, so we cannot put @Component on them. Others need settings when they are built. Spring must still supply them to the classes that ask.

When you cannot annotate a class: library types such as Clock

A library type is a class you use but did not write, such as java.time.Clock from the JDK or a class from a Maven dependency. You cannot put @Component on it, because its source code is not yours.

OrderDateService asks for a Clock in its constructor, but nothing registers one. Start the app and read the report.

Example 1 · src/main/java/com/shoplite/lab/OrderDateService.java

Runs in: the di-lab practice project (Spring Boot 4.1)

OrderDateService.javaJava
package com.shoplite.lab;
import java.time.Clock;import java.time.LocalDate;
import org.springframework.stereotype.Service;
@Servicepublic class OrderDateService {
    private final Clock clock;
    public OrderDateService(Clock clock) {        this.clock = clock;    }
    public LocalDate today() {        return LocalDate.now(clock);    }}
Sample output
2026-10-16T10:20:21.234+05:30 ERROR 8888 --- [di-lab] [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.shoplite.lab.OrderDateService required a bean of type 'java.time.Clock' that could not be found.


Action:

Consider defining a bean of type 'java.time.Clock' in your configuration.

What this code does

  • OrderDateService asks for a Clock, but no bean of that type exists: the JDK class has no @Component, and nobody registered one.
  • The Action line, "Consider defining a bean of type 'java.time.Clock'", is exactly what a @Bean method does.

Clock is a good first case. It tells code what "now" is, and ShopLite needs it for order dates and sale end times. When a class asks for a Clock and nothing registers one, the app fails at startup with the report you know from the stereotype lesson.

Some objects also need settings when they are built: a time zone, a date pattern, a fee. @Component cannot pass those in. Both cases are solved by a @Bean method.

A @Configuration class with @Bean methods

@Configuration marks a class whose job is to define beans. Each method marked @Bean builds one object and returns it, and Spring keeps the result as a singleton bean. The class is itself a @Component.

AppConfig defines two beans with @Bean methods: a Clock and a DecimalFormat for rupee amounts. The runner asks for both in its constructor.

Example 2 · AppConfig.java, ConfigCheckRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

AppConfig.javaJava
package com.shoplite.lab;
import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.time.Clock;import java.time.ZoneId;import java.util.Locale;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class AppConfig {
    @Bean    public Clock clock() {        return Clock.system(ZoneId.of("Asia/Kolkata"));    }
    @Bean    public DecimalFormat priceFormat() {        return new DecimalFormat("Rs #,##0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));    }}
package com.shoplite.lab;
import java.math.BigDecimal;import java.text.DecimalFormat;import java.time.Clock;import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;
@Componentpublic class ConfigCheckRunner implements CommandLineRunner {
    private final Clock clock;    private final DecimalFormat priceFormat;    private final ApplicationContext context;
    public ConfigCheckRunner(Clock clock, DecimalFormat priceFormat, ApplicationContext context) {        this.clock = clock;        this.priceFormat = priceFormat;        this.context = context;    }
    @Override    public void run(String... args) {        System.out.println("Clock bean names: " + Arrays.toString(context.getBeanNamesForType(Clock.class)));        System.out.println("Clock zone: " + clock.getZone());        System.out.println("Format bean names: " + Arrays.toString(context.getBeanNamesForType(DecimalFormat.class)));        System.out.println("Laptop price: " + priceFormat.format(new BigDecimal("149999")));    }}
Output
Clock bean names: [clock]
Clock zone: Asia/Kolkata
Format bean names: [priceFormat]
Laptop price: Rs 149,999.00

What this code does

  • AppConfig defines two beans: clock (the system clock in the Asia/Kolkata zone) and priceFormat (a DecimalFormat for rupee amounts). The bean names are the method names.
  • The runner asks for Clock and DecimalFormat in its constructor, exactly as it would ask for your own beans. It cannot tell how they were registered.
  • DecimalFormatSymbols.getInstance(Locale.ENGLISH) fixes the comma and dot, so the price prints the same on every computer.

Spring calls each @Bean method once at startup. The bean name is the method name: clock() gives a bean named clock, and @Bean("warehouseZone") sets a different name. The return type is the bean's type, so any class can ask for a Clock in its constructor and get this one.

@Configuration is itself a @Component, so component scanning finds the class. In ShopLite such classes live in com.shoplite.common.config.

Predict the output

Predict the @Bean result

Choose the answer.

Round 1 of 2

Which bean names do the two @Bean methods give?

@Configuration
public class AppConfig {
@Bean
public Clock clock() { ... }
@Bean("warehouseZone")
public ZoneId zone() { ... }
}
A @Bean method in a class without @Configuration (and without any stereotype) is never called: Spring never sees the class. Practice 6 shows that bug.

@Bean method parameters are injected

A @Bean method is a method in a @Configuration class whose return value Spring keeps as a bean. Its parameters are filled with other beans, exactly like constructor parameters.

diwaliSale(Clock clock) needs the Clock bean. Spring passes it in, and the SaleWindow class stays free of Spring annotations.

Example 3 · SaleWindow.java, AppConfig.java, SaleRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

SaleWindow.javaJava
package com.shoplite.lab;
import java.time.Clock;import java.time.LocalDateTime;
// A plain class: no annotation. AppConfig decides how to build it.public class SaleWindow {
    private final Clock clock;    private final String name;    private final LocalDateTime start;    private final LocalDateTime end;
    public SaleWindow(Clock clock, String name, LocalDateTime start, LocalDateTime end) {        this.clock = clock;        this.name = name;        this.start = start;        this.end = end;    }
    public boolean isOn() {        LocalDateTime now = LocalDateTime.now(clock);        return !now.isBefore(start) && now.isBefore(end);    }
    public String describe() {        return name + " from " + start + " to " + end;    }}
package com.shoplite.lab;
import java.time.Clock;import java.time.LocalDateTime;import java.time.ZoneId;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class AppConfig {
    @Bean    public Clock clock() {        return Clock.system(ZoneId.of("Asia/Kolkata"));    }
    @Bean    public SaleWindow diwaliSale(Clock clock) {   // Spring passes the Clock bean in        System.out.println("Building diwaliSale with a clock in " + clock.getZone());        return new SaleWindow(clock, "Diwali sale",                LocalDateTime.of(2026, 11, 5, 0, 0), LocalDateTime.of(2026, 11, 12, 0, 0));    }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class SaleRunner implements CommandLineRunner {
    private final SaleWindow diwaliSale;
    public SaleRunner(SaleWindow diwaliSale) {        this.diwaliSale = diwaliSale;    }
    @Override    public void run(String... args) {        System.out.println(diwaliSale.describe());    }}
Output
Building diwaliSale with a clock in Asia/Kolkata
Diwali sale from 2026-11-05T00:00 to 2026-11-12T00:00

What this code does

  • SaleWindow is a plain class with no annotation. AppConfig.diwaliSale builds it from the Clock bean and two fixed dates, and its bean name is diwaliSale.
  • Spring creates the clock bean first, because diwaliSale needs it, then calls diwaliSale(clock). The first output line shows the call.
  • The runner receives the SaleWindow by type through its constructor.

Spring finds a bean of each parameter type and passes it in. This is how you build a plain class that needs both beans and fixed values: the method passes the Clock and the sale dates to the constructor.

Inside a @Configuration class you may also call another @Bean method directly, such as clock(); Spring makes sure you still get the one shared bean. Parameters are clearer, so ShopLite uses them.

A Clock bean makes time-based code testable

Clock.fixed(instant, zone) is a clock stuck at one instant. A test passes it to code that reads LocalDateTime.now(clock), so the test chooses what "now" is, on any day.

FlashSaleService reads the time only through the Clock it receives. The runner and a JUnit test build it with new and a fixed clock.

Example 4 · FlashSaleService.java, FixedClockRunner.java

Runs in: the di-lab practice project (Spring Boot 4.1)

FlashSaleService.javaJava
package com.shoplite.lab;
import java.time.Clock;import java.time.LocalDateTime;
import org.springframework.stereotype.Service;
@Servicepublic class FlashSaleService {
    private static final LocalDateTime SALE_ENDS = LocalDateTime.of(2026, 10, 20, 23, 59);
    private final Clock clock;
    public FlashSaleService(Clock clock) {        this.clock = clock;    }
    public String status() {        LocalDateTime now = LocalDateTime.now(clock);        if (now.isAfter(SALE_ENDS)) {            return "Sale over";        }        long hoursLeft = java.time.Duration.between(now, SALE_ENDS).toHours();        return "Sale on, " + hoursLeft + " hours left";    }}
package com.shoplite.lab;
import java.time.Clock;import java.time.LocalDateTime;import java.time.ZoneId;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class FixedClockRunner implements CommandLineRunner {
    @Override    public void run(String... args) {        ZoneId india = ZoneId.of("Asia/Kolkata");        for (LocalDateTime moment : new LocalDateTime[] {                LocalDateTime.of(2026, 10, 19, 23, 59),                LocalDateTime.of(2026, 10, 20, 21, 0),                LocalDateTime.of(2026, 10, 21, 9, 0)}) {            Clock fixed = Clock.fixed(moment.atZone(india).toInstant(), india);            FlashSaleService service = new FlashSaleService(fixed);   // plain new, no Spring            System.out.println(moment + " -> " + service.status());        }    }}
Output
2026-10-19T23:59 -> Sale on, 24 hours left
2026-10-20T21:00 -> Sale on, 2 hours left
2026-10-21T09:00 -> Sale over

What this code does

  • FlashSaleService never calls LocalDateTime.now() without a clock. In the app it gets the real Clock bean from AppConfig (the clock() method from Example 2).
  • The runner builds three services with new and a fixed clock each: one day before the end, three hours before, and the next morning. The answers are the same whatever day you run it.

Example 5 · src/test/java/com/shoplite/lab/FlashSaleServiceTest.java

Runs in: the di-lab practice project (Spring Boot 4.1)

Java
package com.shoplite.lab;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Clock;import java.time.LocalDateTime;import java.time.ZoneId;
import org.junit.jupiter.api.Test;
class FlashSaleServiceTest {
    private static final ZoneId INDIA = ZoneId.of("Asia/Kolkata");
    private static FlashSaleService at(LocalDateTime moment) {        Clock fixed = Clock.fixed(moment.atZone(INDIA).toInstant(), INDIA);        return new FlashSaleService(fixed);    }
    @Test    void showsHoursLeftDuringTheSale() {        assertEquals("Sale on, 2 hours left", at(LocalDateTime.of(2026, 10, 20, 21, 0)).status());    }
    @Test    void saysOverOneMinuteAfterTheEnd() {        assertEquals("Sale over", at(LocalDateTime.of(2026, 10, 21, 0, 0)).status());    }}
Sample output (mvn test, shortened)
[INFO]  T E S T S
    ...
[INFO] Running com.shoplite.lab.FlashSaleServiceTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.154 s -- in com.shoplite.lab.FlashSaleServiceTest
    ...
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
    ...
[INFO] BUILD SUCCESS

What this code does

  • The same idea as a JUnit test: at(...) builds a FlashSaleService whose clock is stuck at a chosen moment.
  • The second test checks the exact edge, midnight right after the sale ends. Without a Clock you could only test this by running the test at midnight.

Code that calls LocalDateTime.now() directly reads the computer's real clock, so a test of "the sale is over" passes or fails depending on the day you run it. With LocalDateTime.now(clock) the app gets the real clock from the @Bean method, and a test can check one minute before the end, during the sale and after it.

Use one clock for the whole app, with an explicit zone such as Asia/Kolkata. Then order dates do not change when the server runs in another time zone.

@Component scanning or @Bean method: which one?

Both register beans, and other classes inject them the same way. The choice is about who owns the class and how it is built.

Prefer @Component, @Service and the other stereotypes for your own classes: the class says what it is, and scanning finds it. Use a @Bean method for library types, for objects that need settings at creation time, and for a few related objects you want to see together.

Do not do both for one class. A class with @Component that is also returned from a @Bean method becomes two beans of the same type, and an injection point that asks for that type fails with "required a single bean, but 2 were found". The next lesson covers that error.

  • Your own service, repository, controller or helper → stereotype annotation.
  • Clock, DateTimeFormatter, a client from a library → @Bean method.
  • A plain class that needs fixed values when built → @Bean method.

Find the bug

Find the @Bean bug

Each setup fails at startup. Tap the wrong line.

ReceiptService fails: "required a single bean, but 2 were found".

Round 1 of 2

Next step

Check your understanding

11 quick questions