Video in progress

Junior 🌱 Spring

How do you declare a bean with @Configuration and @Bean, and when do you need it?

The object returned by a @Bean method in a @Configuration class becomes a bean. You need it for library classes you didn't write yourself, or for objects that are complicated to create.

📖 Answer

On your own class you put @Component. But you can't put annotations on library classes like ObjectMapper, RestClient or Clock. For them:

@Configuration
public class AppConfig {

    @Bean
    public Clock clock() {
        return Clock.system(ZoneId.of("Asia/Tashkent"));
    }

    @Bean
    public RestClient paymentClient(RestClient.Builder builder,
                                    @Value("${payment.url}") String url) {
        return builder.baseUrl(url).build();
    }
}

The bean name is the method name (clock, paymentClient). Method parameters get injected too.

Making Clock a bean is a good habit: if you write Instant.now(clock) instead of Instant.now(), you can freeze time in tests with no trouble.

A @Configuration class gets wrapped in a CGLIB proxy, so even if you call one @Bean method from inside another, you don't get a new object — the same singleton comes back.