'Why I can replace @RestContoller with @Component and it still works?

Can someone explain why replacement of RestController annotation with Component has no any visible effect in my case? My controller:

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @PostMapping("")
    public Employee saveEmployee(@Valid @RequestBody Employee employee) {
        return employeeService.save(employee);
    }


    ...

This works in the same way:

@Component
@ResponseBody
@RequestMapping("/api/employees")
public class EmployeeController {

...


Solution 1:[1]

The not-in-depth description of individual annotations would be:

  • @RequestMapping registers your class for servlet mapping.
  • @Component registers your class for dependency injection.
  • @ResponseBody will add the return value of the method to the HTTP response body.

1st case - @RestController registers your class for DI and adds @ResponseBody annotation to it, @RequestMapping registers class for servlet mapping.

2nd case - @Component registers your class for DI and you added a manual @ResponseBody annotation to it, @RequestMapping registers class for servlet mapping.

Both of the cases above do the same thing, so that's why it 'just works'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Desomph