Backend Development 7 min read

Using @Service to Replace @Controller in Spring Boot

In Spring Boot, a class annotated with @Service can act as a web controller if it is discovered by component scanning and carries @RequestMapping (or method‑level mapping) annotations, allowing HTTP requests to be handled just like a traditional @Controller‑annotated bean.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Using @Service to Replace @Controller in Spring Boot

In Spring Boot development, @Controller and @Service are the two most frequently used annotations. This article explores whether @Service can be used to annotate a controller layer and still handle web requests.

It explains that @Controller marks a class as a web controller handling HTTP requests, while @Service marks a class as a service handling business logic. Both annotations are detected by component scanning based on @SpringBootApplication, which includes @EnableAutoConfiguration, @ComponentScan, and @Configuration.

Because @ComponentScan registers any class annotated with @Controller, @Service, @Repository, or @Component, a class annotated only with @Service can still be registered in the Spring container. If the class also carries @RequestMapping (or method‑level mapping annotations), Spring MVC will treat it as a handler.

Example code:

@Service
@RequestMapping("/ts")
public class ServiceController {
    @Autowired
    UserMapper userMapper;

    @GetMapping("get-services")
    @ResponseBody
    public User getServices() {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, "zhangSan"));
        return user;
    }
}

A GET request to http://localhost:8080/ts/get-services returns a JSON payload with the user data, demonstrating that the @Service‑annotated class successfully handles the request.

The article further details the bean registration process: SpringApplication.run creates the application context, ConfigurationClassPostProcessor scans for bean definitions, and AbstractHandlerMethodMapping binds URLs to handler methods based on @RequestMapping metadata.

In summary, as long as a class is registered as a bean (e.g., via @Service) and contains request‑mapping annotations, Spring Boot can route HTTP requests to it just like a traditional @Controller.

JavaAnnotationsSpringBootControllerDependencyInjectionService
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.