'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:
@RequestMappingregisters your class for servlet mapping.@Componentregisters your class for dependency injection.@ResponseBodywill 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 |
