@Component is a Spring annotation that is used to indicate that a class is a component. Components are objects that make up the structure of an application and are responsible for performing specific tasks. They are typically used to represent services, controllers, repositories, and other types of objects that are used to implement business logic in a Spring application.
How to use @Component Annotation
To use the @Component annotation in a Spring Boot Rest application with Maven, you will first need to add the Spring Boot starter dependencies to your project. This can be done by adding the following lines to your pom.xml file:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
Once the dependencies are added, you can create a class that you want to mark as a component. For example, let’s say you want to create a service class that is responsible for managing users. You can do this by creating a class called UserService and annotating it with @Component:
@Component public class UserService { // implementation goes here }
Once the class is marked as a component, it can be autowired into any other class that needs to use it. For example, if you have a controller class that needs to use the UserService class, you can autowire it like this:
@RestController public class UserController { @Autowired private UserService userService; // controller methods go here } }
Lifecycle of a @Component
In the world of Spring, understanding the lifecycle of a @Component is crucial. It’s like understanding the stages of life from birth to death for a living organism. In this section, we will delve into the lifecycle of a Spring @Component, from creation to destruction.
Creation and Initialization
The lifecycle of a @Component begins with its creation. When your Spring application starts up, Spring’s component scanning mechanism kicks into action. It scans the project for classes annotated with @Component and its specializations (@Service, @Repository, @Controller, etc.). Once it finds these classes, it creates instances, also known as beans, and registers them in the Spring application context. This process is often referred to as “instantiation”.
After a bean is instantiated, it goes through a process of initialization. If your @Component bean has any methods annotated with @PostConstruct, these methods are executed after the bean has been constructed and dependency injection is complete. This is a perfect place to put any setup code that your component might need.
Here’s an example:
@Component public class UserService { @PostConstruct public void init() { // initialization logic goes here } // rest of the class implementation }
In this example, the init()
method will be called once the UserService bean is created and all its dependencies are injected.
Usage
Once your @Component bean is created and initialized, it’s ready to be used. It can be injected into other components using Spring’s @Autowired annotation, as we’ve seen in the previous sections. The bean will exist and be available for use as long as the application context is running.
Destruction
The final stage in the lifecycle of a @Component is destruction. When the application context is being closed, Spring checks if your @Component bean has any methods annotated with @PreDestroy. If such methods exist, they are called. This gives you a chance to clean up any resources that your component might have acquired.
Here’s an example:
@Component public class UserService { @PostConstruct public void init() { // initialization logic goes here } @PreDestroy public void cleanup() { // cleanup logic goes here } // rest of the class implementation }
In this example, the cleanup()
method will be called when the application context is being closed.
Default Scope of a @Component
In Spring, every bean has a scope, which determines the lifecycle and visibility of that bean. For beans annotated with @Component, the default scope is “singleton”. But what does this mean? Let’s delve into it.
Singleton Scope
When a bean is a singleton, it means that only one instance of that bean is created per Spring IoC container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that bean will return the cached object. This is the default scope for a @Component.
Here’s an example:
@Component public class UserService { // UserService is a singleton bean by default }
In this example, Spring will create a single instance of UserService for each application context.
Changing the Scope
While singleton is the default, Spring allows you to change the scope of a @Component. You can do this using the @Scope annotation. Spring supports several scopes, but the most commonly used are “singleton” and “prototype”.
If you set the scope of a bean to “prototype”, a new instance will be created every time the bean is requested.
Here’s an example:
@Component @Scope("prototype") public class UserService { // A new UserService will be created every time one is needed }
In this example, a new UserService will be created each time one is requested from the application context.
Remember, the scope of a bean determines the lifecycle of its instances, so choose the scope carefully based on the needs of your application. Understanding the scope of a @Component and how to change it gives you more control over how and when your components are created and destroyed.
@Component vs Other Stereotype Annotations
The @Component annotation in Spring is a general-purpose stereotype annotation indicating that a class is a Spring-managed component. Its role is to allow Spring to automatically detect our custom beans using classpath scanning.
There are other stereotype annotations in Spring like @Repository, @Service, and @Controller. These are specializations of @Component, meaning they carry the same functionality but are used in more specific cases.
Similarities
- All of these annotations (@Component, @Repository, @Service, and @Controller) are used to auto-detect and auto-configure beans using classpath scanning.
- They all make the class eligible for Spring’s auto-proxying, which can be used with aspects or other Spring proxying functionality.
- They are all used to annotate classes at the class level.
Differences
The main difference between @Component and the other annotations is in the semantics. While @Component is a generic stereotype for any Spring-managed component, @Repository, @Service, and @Controller serve as a specialization of @Component, each carrying additional semantics for specific use cases:
- @Repository: This annotation is a marker for any class that fulfills the role of repository or Data Access Object (DAO). This annotation has a special feature: it can convert database-related exceptions into Spring’s DataAccessException.
- @Service: This annotation is used in your service layer and annotates classes that perform business logic.
- @Controller: This annotation is used in Spring MVC to annotate classes that act as a controller in your application.
In summary, while you can use @Component for any Spring-managed component, it’s better to choose @Repository, @Service, or @Controller for classes that specifically act as repositories, services, or controllers, respectively. This makes your program easier to understand and provides better context to Spring about the role of your component.
Summary
In this tutorial, we’ve delved into the @Component annotation in Spring, a fundamental aspect of creating Spring-managed components. Here are the key takeaways:
- @Component is a general-purpose stereotype annotation that marks a class as a Spring-managed component. It allows Spring to automatically detect our custom beans using classpath scanning.
- The @Component annotation plays a crucial role in Spring’s Dependency Injection mechanism. Classes marked with @Component can be autowired into other components, allowing Spring to handle the lifecycle and dependencies of your beans.
- The lifecycle of a @Component is managed by the Spring IoC container. From creation and initialization, through its usage, to its destruction, Spring takes care of your components when they are annotated with @Component.
- While @Component is the default scope, Spring allows you to change the scope of a @Component using the @Scope annotation. By default, a single instance of a @Component (singleton scope) exists per Spring IoC container.
- @Component is a generic annotation, and Spring provides specialized annotations like @Service, @Repository, and @Controller for specific use cases. These annotations carry additional semantics, making your program easier to understand and providing better context to Spring about the role of your component.
This tutorial has provided a comprehensive overview of the @Component annotation. However, to fully leverage the power of Spring, it’s important to understand other stereotype annotations like @Service, @Repository, and @Controller. We invite you to continue your learning journey by reading our tutorial on Spring Boot Stereotype Annotations.
Thank you for reading, and happy coding!