Sobes.tech
Junior — Middle

When is it recommended to use the @Bean annotation in Spring framework?

sobes.tech AI

Answer from AI

The @Bean annotation in Spring is used for explicitly defining a bean within a configuration class. It is recommended to use it in the following cases:

  • When you need to create a bean that cannot be automatically detected through component scanning (@Component and similar).
  • For configuring third-party libraries or classes that are not annotated with Spring-specific annotations.
  • When more fine-grained control over bean creation and configuration is required, such as setting parameters through methods.

Example:

@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
        ds.setUsername("user");
        ds.setPassword("pass");
        return ds;
    }
}
When is it recommended to use the @Bean annotation in… - sobes.tech