What's the difference between @Component, @Repository & @Service annotations in Spring?

后端 未结 29 2174
时光说笑
时光说笑 2020-11-22 00:33

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

29条回答
  •  温柔的废话
    2020-11-22 01:03

    Good enough answers are here to explain the whats-the-difference-between-component-repository-service-annotations. I would like to share the difference between @Controller & @RestController

    @Controller vs RestController

    @RestController:

    • This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically. so we do not have to add @ResponseBody to our mapping methods. That means @ResponseBody is default active.
    • If you use @RestController you cannot return a view (By using Viewresolver in Spring/Spring-Boot)
    • @RestController also converts the response to JSON/XML automatically as @ResponseBody makes the returned objects to something that could be in the body, e.g. JSON or XML

    @Controller

    • @Controller is used to mark classes as Spring MVC Controller. This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
    • @Controller you can return a view in Spring web MVC.

    More Detailed View

提交回复
热议问题