Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
In Spring Framework, @Component
, @Repository
, @Service
, and @Controller
are annotations used to indicate that a class should be automatically detected and registered as a bean in the Spring container. Although they all serve the same primary purpose (auto-detection of beans), they have different semantic meanings and sometimes come with added special functionalities.
Let's break them down:
@Component:
@Repository
, @Service
, or @Controller
.@Repository:
DataAccessException
.@Service:
@Controller:
@Component
.@Controller
beans can make use of other annotations like @RequestMapping
, @GetMapping
, @PostMapping
, etc., to map web requests to specific methods.These annotations also assist with clear layering in the application architecture, indicating clear roles and responsibilities for classes. For example, separating concerns via a controller, service, repository pattern.
All these annotations are essentially specializations of @Component
. Hence, classes annotated with any of these annotations will be auto-detected during classpath scanning.
Starting with Spring 4.x, there's also @RestController
which is a combination of @Controller
and @ResponseBody
. This means the response returned by methods in a @RestController
class doesn't need to be a view (like a JSP or Thymeleaf template); it can be a domain object, and Spring will handle converting it to JSON or XML, depending on the request's Accept header.
In summary, while these annotations technically accomplish the same thing (bean registration and autodetection), they provide semantic clarity about the role of a class in the application and, in some cases, come with additional features tailored to that role.
Examples of @Component
, @Repository
, @Service
, @Controller
in Spring:
// @Component @Component public class MyComponent { // General-purpose bean }
// @Repository @Repository public class MyRepository { // Data access bean }
// @Service @Service public class MyService { // Service layer bean }
// @Controller @Controller public class MyController { // Web layer bean }
In a Spring application, you would use these annotations based on the role of each class.