Sobes.tech
Senior

Will @RequestMapping work if the class is only annotated with @Component?

sobes.tech AI

Answer from AI

The @RequestMapping annotation in Spring MVC is used for handling HTTP requests and is usually used together with annotations that register the class as a controller, such as @Controller or @RestController.

If the class is only marked with @Component, then Spring will register it as a regular component, but not as a controller, and @RequestMapping will not work — requests will not be routed to the methods of this class.

For @RequestMapping to work, the class must be recognized by Spring as a controller, i.e., have the @Controller or @RestController annotation.

Example:

@Component // this is not enough
@RequestMapping("/api")
public class MyController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello";
    }
}

// Correct:
@RestController
@RequestMapping("/api")
public class MyController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello";
    }
}

Thus, without @Controller or @RestController, @RequestMapping will not work.