Using @Service to Replace @Controller in Spring Boot: Principles and Example
This article examines whether the @Service annotation can replace @Controller in Spring Boot by presenting a functional example, explaining the component‑scanning and request‑mapping mechanisms that allow a @Service‑annotated class to handle HTTP requests just like a controller.
In Spring Boot development the @Controller and @Service annotations are the most frequently used, but this article explores whether @Service can replace @Controller for handling web requests.
We define a class ServiceController annotated with @Service and @RequestMapping, inject a UserMapper via @Autowired, and expose a GET endpoint /ts/get-services that returns a User object.
@Service
@RequestMapping("/ts")
public class ServiceController {
@Autowired
private UserMapper userMapper;
@GetMapping("get-services")
@ResponseBody
public User getServices() {
User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
.eq(User::getUsername, "zhangSan"));
return user;
}
}Sending a GET request to http://localhost:8080/ts/get-services returns JSON data, demonstrating that the @Service‑annotated class can handle HTTP requests just like a @Controller.
The underlying reason is that Spring’s component scanning (triggered by @SpringBootApplication) registers both @Controller and @Service beans, and the request mapping infrastructure ( AbstractHandlerMethodMapping ) processes any bean that carries @RequestMapping, regardless of whether it is marked as a controller.
Thus, as long as a class is discovered as a bean and contains mapping annotations, Spring MVC will treat it as a handler, allowing @Service to serve the same purpose as @Controller.
In summary, @Service can be used to annotate a class that handles web requests, provided it is scanned and contains @RequestMapping (or related) annotations; the request handling flow remains identical to that of a traditional @Controller.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.