Can @Service Replace @Controller in Spring Boot? A Deep Dive
This article explores whether the @Service annotation can replace @Controller in Spring Boot, demonstrates a working example, explains the underlying bean registration process, and clarifies how Spring’s component scanning and request mapping enable such unconventional usage.
Preface
In Spring Boot development,
@Controllermarks a controller class that handles web requests, while
@Servicemarks a service class responsible for business logic. This article investigates whether a class annotated with
@Servicecan be used to handle controller responsibilities.
Using @Service Instead of @Controller
We define a
ServiceControllerclass annotated with
@Serviceand
@RequestMapping("/ts"). The class autowires a
UserMapperto interact with the data layer and exposes a
getServicesmethod via
@GetMapping("get-services"):
<code>@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;
}
}
</code>Sending a GET request to
http://localhost:8080/ts/get-serviceswith PostMan returns the expected JSON response, confirming that the
@Service-annotated class can handle HTTP requests just like a traditional controller.
Underlying Mechanism
Both
@Controllerand
@Serviceare detected by Spring’s component scanning, which is triggered by the
@SpringBootApplicationmeta‑annotation (composed of
@EnableAutoConfiguration,
@ComponentScan, and
@Configuration). Classes annotated with either stereotype that reside in the main application package or its sub‑packages are registered as beans in the Spring container.
During startup,
ConfigurationClassPostProcessorprocesses bean definitions, and
AbstractHandlerMethodMappinglater maps URLs to methods based on
@RequestMapping(or its shortcut annotations). As long as the class is a bean and carries request‑mapping annotations, Spring MVC can treat it as a controller, regardless of whether it is marked with
@Controlleror
@Service.
Summary
In Spring Boot,
@Controllerand
@Serviceare both component stereotypes that can be discovered and registered by the container. When a
@Service-annotated class also carries
@RequestMapping(or related) annotations, Spring MVC will route HTTP requests to its methods, effectively allowing
@Serviceto function as a controller. This behavior stems from Spring’s component scanning, bean registration, and the request‑mapping mechanism within
AbstractHandlerMethodMapping.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.