Sobes.tech
Junior — Middle

What are the advantages and disadvantages of using the @Component annotation compared to @Bean?

sobes.tech AI

Answer from AI

The @Component annotation is used for automatic detection and registration of beans in Spring through classpath scanning (component scanning). The @Bean annotation is used for explicit bean definition within a configuration class.

Advantages of @Component:

  • Simplifies configuration, does not require explicit bean declaration in configuration.
  • Suitable for classes that can be automatically detected.
  • Allows the use of stereotypes (@Service, @Repository, @Controller), which improves readability and semantics.

Disadvantages of @Component:

  • Less control over bean creation (e.g., difficult to set constructor parameters or creation logic).
  • Requires component scanning to be enabled.

Advantages of @Bean:

  • Full control over bean creation, can use any logic and parameters.
  • Can create beans from third-party classes that cannot be annotated.

Disadvantages of @Bean:

  • Requires explicit declaration of each bean in configuration, which can be verbose.

Example of using @Bean:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

Example of using @Component:

@Component
public class MyServiceImpl implements MyService {
    // implementation
}