@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 } }
That’s all there is to it! With the @Component annotation, you can easily create and inject components into your Spring Boot Rest application using Maven.
To learn more, check out Spring Boot tutorials page.