Sobes.tech
Junior

What is the purpose of the @Bean annotation in the Spring Framework?

sobes.tech AI

Answer from AI

The @Bean annotation is used in Spring to declare methods that produce beans (objects managed by the Spring IoC container). A method annotated with @Bean is executed by Spring, and its return value is registered as a bean in the application context.

Main use cases:

  • Configuring third-party libraries: When it is not possible to apply Spring annotations (@Component, @Service, etc.) to classes from third-party libraries.
  • Fine-tuning bean creation: When complex initialization logic is required for an object, which is difficult or impossible to implement using annotations.
  • Conditional bean creation: Along with @Conditional annotations to create beans based on certain conditions.

Example of creating a bean with @Bean:

// In a class annotated with @Configuration
@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        // Complex logic for creating DataSource
        return new com.zaxxer.hikari.HikariDataSource(); // Example
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        // Configuring RestTemplate
        return builder.setConnectTimeout(Duration.ofSeconds(5))
                      .setReadTimeout(Duration.ofSeconds(5))
                      .build();
    }
}

Beans declared with @Bean are available for dependency injection into other Spring components. By default, the bean name matches the method name, but it can be explicitly set using the name or value attribute.

// Explicitly setting the bean name
@Bean(name = "myCustomRestTemplate")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    // ...
    return builder.build();
}