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 the Spring framework, @Controller
and @Service
are both stereotype annotations that allow the Spring container to detect and register beans automatically. While they both serve this primary purpose, they have distinct roles and usages in a typical Spring application, which denote different layers or components of an application.
Here's a breakdown of their differences:
@Controller:
Controller
part in the Model-View-Controller (MVC) pattern. Such classes are responsible for processing incoming HTTP requests, invoking business logic, returning responses, and (in traditional web apps) choosing which view should be displayed.@RequestMapping
, @GetMapping
, @PostMapping
, etc., to define routing information.@Controller public class UserController { @Autowired private UserService userService; @GetMapping("/users") public String listUsers(Model model) { model.addAttribute("users", userService.findAll()); return "userList"; } }
@Service:
@Service
beans are typically used to implement core functionality like computations, database operations, invoking APIs, etc. They don't handle HTTP requests directly but might be invoked by controllers.@Transactional
).@Service public class UserService { @Autowired private UserRepository userRepository; public List<User> findAll() { return userRepository.findAll(); } }
@Controller
is oriented toward processing HTTP requests and responses, serving as a bridge between the user and the application's backend.
@Service
, on the other hand, is all about implementing the application's business logic or interfacing with databases and other services.
In a layered application architecture, controllers rely on services to execute the required operations and return results. Controllers should ideally be lightweight and delegate most of the heavy lifting to services or other components. The separation ensures a clear distinction of responsibilities, making the codebase more maintainable and testable.
Examples of @Controller
and @Service
in a Spring application:
@Controller
:@Controller public class MyController { @GetMapping("/hello") public String sayHello() { return "hello"; } }
@Service
:@Service public class MyService { public String performBusinessLogic() { // Business logic return "result"; } }
In this example, @Controller
handles a web request, while @Service
encapsulates business logic.