Skip to content
thesarfo

Reference

Spring Start Here: Common Annotations

What @Component, @Service, @Repository, @Controller, @ResponseBody, and @RestController each actually mean.

views 0

Some common annotations in Spring: @Required, @Autowired, @Configuration, @ComponentScan, @Bean, @Component, @Controller, @Service, @Repository, @ResponseBody.

  1. @Component — a class-level annotation marking a class as a Spring-managed component. A component is responsible for some operation. Spring provides three more specific annotations for marking a class as a component, depending on its role:

  2. @Service — the class holds business logic or services. Beyond that (typically the service layer), there’s no other special behavior tied to this annotation.

  3. @Repository — the class deals with CRUD operations (create, read, update, delete) — mostly DAOs or repositories that talk to databases.

  4. @Controller — the class is a front controller, responsible for handling user requests and returning appropriate responses. Mostly used with REST web services.

  5. @ResponseBody — tells the dispatcher servlet that this method doesn’t return a view name, but the HTTP response directly.

To avoid repeating @ResponseBody on every method, Spring offers @RestController — a combination of @Controller and @ResponseBody.