Spring Component Annotation

Sachith Ariyathilaka
2 min readOct 8, 2023

Spring Annotations is used to provide some meta data about the programs. In this blog, let’s discuss the @Component annotation used in the spring.

@Component is a class-level annotation that is used to denote a class as a component. A component is responsible for some operations of the application. We can use this annotation anywhere in the application to mark the beans as Spring’s managed component. For example, we can determine the Open API configuration as a component class. Other than these specific components, the spring framework provides three special annotations that are used to make a class a component, which are @Controller, @Service, and @Repository. In other words, @Component annotation is a general-purpose stereotype annotation, while @Controller, @Service, and @Repository are the special types of @Component annotations. Also, this annotation can be identified as scan auto-detection and dependency injection for BeanDefinition.

01. @Controller Annotation: This annotation is a specialization of the @Component annotation, which indicates that a particular class serves the role of controller. It is used to mark a class as a web request handler. This is the presentation layer of the spring MVC. As we discussed before, this annotation is also a stereotype annotation.

There is another type of @Controller specification called @RestController, which is used in Restful web services and is a combination of @Controller and @ResponseBody annotations. When we consider the main difference between the @Controller and @RestController, the @Controller returns the view of the spring MVC, while the @RestController does not return any view.

02. @Service Annotation: This annotation is used when the class contains the business logic of the application. This is also a specialization of the @Component annotation. Mainly, this is used to mark class as a service provider. As mentioned before, this annotation is also a stereotype annotation.

03. @Repository Annotation: This annotation is used when the class provides the CRUD operations of the application. This is also a specialisation of the @Component annotation. Mainly, this is used to mark the interface as a data access provider. Mainly, we use these types of annotations at the JPA level of the application. As mentioned before, this annotation is also a stereotype annotation.

The following diagram illustrates the key differences between the @Controller, @Service, and @Repository annotations.

--

--