Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download a Free Sample PDF

Difference between @Component, @Controller, @Service, and @Repository in Spring

Hello guys if you are wondering what is the difference between @Component, @Controller@Service, and @Reposistory annotation in Spring Framework then you have come to the right place. In the past, I have shared 15 Spring Boot Interview Questions and 30 Spring MVC questions and in this article, I am going to answer the fundamental and popular Spring questions about @Component, @Controller@Service, and @Repository annotation, but before we go into differences, let's understand the similarity first.

All three Spring annotations of them are used to make a Java class a Spring bean, something which is managed by Spring Framework and all of them are stereotype annotation in Spring Framework. @Component is used for any general class while other three annotations are the specialized form of @Component annotation.

For example, a class in Spring framework (spring bean) annotated with the @Controller annotation is supposed to be used to annotate a HTTP controller class in Spring MVC. A class which handles HTTP flow, receives request and send response. 

On the other hand @Service is used for a Spring bean which is used in Service layer. They are responsible for implementing business logic in application. Similarly @Repository annotation is used for a spring bean which is used in Data Access layer. They are responsible for loading and persisting data on database.

The important thing is that these are just guideline, even if you annotate a bean in Service layer with @Componenent, Spring can still find it and create instance of it but its better to use the right annotation so that you can use any other tool which operate on these annotations.  

Spring 2.0 has @Repository annotation, which is used as marker annotation. Currently a bean marked by @Component is also a Spring bean and a bean marked by @Service is also a spring bean, but they can be differentiated in future to associated Service level responsibility like transaction to a bean which is annotated by @Service, while @Component is a general purpose annotation to mark a Java object as Spring managed bean.


Example of @Component, @Controller, @Service and @Repository annotation in Spring Framework

As I said, you can use any of these annotation to mark a Java class as Spring managed bean, but using them in right context  is what you need. Annotating a Service class with @Service gives Spring flexibility to do some automation, which is needed by Service classes e.g. transaction management. Currently Spring provides  

Similar to @Repository annotated bean, which provides automatic exception translation for DAO classes.

Here is a simple example to see, where to use @Component, @Controller, @Service and @Repository annotation is Spring based Java applications. 

Difference between @Component, @Controller, @Service, and @Repository Spring Annotations - Java



1. @Service annotation example in Spring Framework

In our example, we have a class called TradeServiceImpl, which is a Service class, is annotated by @Service annotation. Our DAO class TradeDAOImpl is annotated by @Repository and our Domain object or POJO is annotated by @Component annotation in Spring. It indicate that all these classes are managed by Spring. 

@Service
public class TradeServiceImpl implements TradeService{

  @Autowired
  private TradeDAO tradeDAO;

   
}

When you use this annotation then Spring framework can detect your class and register as a bean in application context, so that, its available for dependency injection in other parts of application. 

Here is another example of @Service annotation in Spring framework 

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public User getUser(int id) {
        // code to retrieve user from the database
    }

    public void updateUser(User user) {
        // code to update user in the database
    }

    // Other service methods
}


Here we have used @Service on UserService class to indicate that this class plays a special role in the application and implement business logic. The method getUser(int id) and updateUser(User user) methods are examples of methods that might be used to retrieve and update user information in the database.


2. @Repository example in Spring

Here is an example of @Reposistory annotation in Spring. In this example we have annotated TradeDAOImpl with @Reposistory annotation to indicate that this is a special Spring bean which is used in Data Access layer and responsible for storing and retrieving data from database. 

@Repository
public class TradeDAOImpl implements TradeDAO {
   // your code
}


Here is one more example of a class annotated with @Repository annotation in Spring Framework

import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.JpaRepository;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

    User findByUsername(String username);

    List<User> findByAge(int age);
}

In this example, the UserRepository interface is annotated with the @Repository annotation, indicating that it is a repository class managed by Spring container. This also allows Spring Framework to automatically detect and register the class as a bean in the application context and  making it available for dependency injection in other parts of the application. 

The UserRepository interface extends the JpaRepository interface, which provides a set of basic CRUD operations (create, read, update, delete) for the User entity. 

The findByUsername(String username) and findByAge(int age) are examples of custom query methods. It's worth noting that the @Repository annotation is a stereotype annotation, which is a special type of annotation provided by Spring that indicates that a class plays a specific role in the application, in this case, for data access. 

Also, Spring Data JPA, which is a Spring module for simplifying the data access layer, provides additional functionality for data access like pagination, sorting and querying without writing custom code.


3. @Component example in Spring

Here is an example of using @Compoenent annotation in Spring Framework. we have used @Compnent on Trade class so that Spring framework can manage this class as Spring Bean and make it available to the other parts of application for dependency injection. 

For example if you create an instance variable of Trade then Spring will use setter injection to assign a Trade class instance to that variable.

@Component
public class Trade{
   
}


4. @Controller annotation Example in Spring

here is an example of a controller class in Spring MVC which is annotated with the @Controller annotation:

Difference between @Component, @Controller, @Service, and @Repository Spring Annotations - Java


In this example, the UserController class is annotated with the @Controller annotation, indicating that it is a controller class managed by Spring. This allows Spring to automatically detect and register the class as a bean in the application context, making it available for handling incoming HTTP requests. 

The getUser(int id) and updateUser(User user) methods are examples of methods that might be used to handle GET and POST requests respectively. They are annotated with @RequestMapping, which maps the request to a specific URL and HTTP method. 

@Autowired annotation is used to inject the UserService bean into the controller, which is used to retrieve and update user information. 

@PathVariable annotation is used to extract the variable from the URI and @RequestBody annotation is used to bind the request body to a method parameter. 

The use of @Controller indicate to any tool or even a Java developer that this class is supposed to handle HTTP request and act as a controller of MVC pattern in your web application. 


Conclusion

In short, @Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.

@Controller is a specific type of component, used in MVC applications and mostly used with @RequestMapping annotation.

@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.

@Service is used to indicate that a class is a Service. Usually the business façade classes that provide some services are annotated with this.

We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.


That's all about the difference between @Component, @Service, and @Repository Spring Annotations. The key thing is when to use which annotation. So for general purpose just use @Component annotation to mark a Java class as bean but if its part of Service layer then use @Service to allow Spring do some magic for you and if its part of persistence layer then use @Repository for similarly purpose. 


Other Java and Spring Articles and Tutorials you may like to explore

Thanks for reading this article so far. If you like my explanation of difference between Component, Service, and Repository annotation in Spring framework and then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.

5 comments:

  1. There is no answer, only example - transactional for @Service. Does any annotation give additional marks, maybe if we use @Controller it gives some additional annotation specially for REST API? The same question for @Repository annotation, does it provide special annotations or something else to work with repo?

    ReplyDelete
    Replies
    1. Hello @Anonymous, as I said, all three can be used to make a Java class as Spring bean the distinction comes from using the most appropriate annotation for the job. For example @Service is for any class which belongs to service layer and @Repository is for any class which belongs to DAO or Persistence layer.

      Now regarding providing any specific functionality, @Repository provides automatic exception translation for DAO classes, which is not possible if you annotate the bean with @service or @Component.

      Delete
    2. Hi, it looks like the annotations only for developers understanding, just like marks(or comments) and almost don't have any semantic load

      Delete
  2. In the above example, Trade class is marked with @component, generally this class is annotated with @Entity.

    ReplyDelete
    Replies
    1. Yes, if you are using Hibernate or Spring Data JPA, you can also annotate with @Entity

      Delete

Feel free to comment, ask questions if you have any doubt.