The annotations @Component and @Bean are both essential in defining and managing beans in Spring applications. When I first started learning Spring Boot, I found it difficult to understand when to use these two annotations. Now, I want to share what I have learned. But first, let’s talk briefly about Spring Boot.
What is Spring Boot?
Spring Boot makes it easy to create standalone Spring applications. It enables you to embed servers like Tomcat and eliminates the need for XML configuration, promoting simplicity and efficiency in developing robust and scalable Spring applications. Spring Boot also includes pre-configured “starter” dependencies, which automatically configure both Spring and third-party libraries wherever possible.
Annotations
@Component
When you use @Component in Spring, you are essentially telling the Spring IoC container to manage instances of the annotated class. The container creates instances, injects dependencies, and handles the lifecycle of these objects.
@Component
public class UserService extends ServiceManager<User, String> {
private final IUserRepository userRepository;
public UserService(IUserRepository userRepository) {
super(userRepository);
this.userRepository = userRepository;
}
@Component must be used for classes so that their objects can be created. Using @Component for interfaces or abstract classes does not make sense.
Why Not for Interfaces or Abstract Classes:
Since interfaces only declare method signatures and abstract classes may have incomplete implementations, attempting to create instances of these types directly wouldn’t be meaningful in the context of the Spring container. The Spring container requires fully implemented classes to instantiate and manage because it needs to know how to create and configure the objects.
Other stereotype with annotations of type @Component
Annotations such as @Service, @Repository, and @Controller essentially extend @Component, inheriting its basic functionality. Spring automatically detects and manages components marked with these annotations.
@Service: Used for service classes, typically where business logic operations are performed.
@Service
public class BudgetService extends ServiceManager<Budget, String> {
private final IBudgetRepository budgetRepository;
public BudgetService(IBudgetRepository budgetRepository) {
super(budgetRepository);
this.budgetRepository = budgetRepository;
}
@Repository: Indicates that the class is a Data Access Object (DAO) component, used for data access classes, such as those dealing with database operations.
@Repository
public interface IUserRepository extends MongoRepository<User, String> {
}
@Controller: Used for controller classes in web applications, managing HTTP requests.
@RestController: A specialized version of @Controller used in RESTful web services.
@RestController
@RequiredArgsConstructor
@RequestMapping(USER)
public class UserController {
private final UserService userService;
@PostMapping(REGISTER)
public ResponseEntity<Boolean> register(@RequestBody @Valid RegisterRequestDto dto) {
return ResponseEntity.ok(userService.register(dto));
}
@Bean
@Bean is used at the method level within a class annotated with @Configuration. This indicates that the method is a factory for creating and configuring a bean. The method annotated with @Bean is responsible for creating an instance of a bean.
@Configuration
public class RabbitConfig {
private final String userRegisterQueue = "user-register-queue";
@Bean
Queue userRegisterQueue() {
return new Queue(userRegisterQueue);
}
In the example above, the ‘userRegisterQueue’ method is creating and returning a new instance of ‘Queue’. The return value of the method becomes the actual bean instance that Spring will manage.
In conclusion, @Component is used for automatic bean registration at the class level, while @Bean is used for manual bean definition at the method level within a configuration class. Stereotype annotations like @Service, @Repository, and @Controller offer specialized functionalities built on top of @Component. Understanding the differences between these annotations is fundamental to effectively leverage the Spring framework’s powerful bean management capabilities in Spring Boot applications.
References:
https://spring.io/projects/spring-boot
https://docs.spring.io/spring-framework/docs