Spring @Component, @Repository, @Service and @Controller Stereotype Annotations

In this tutorial we would discuss about the Stereotype Annotations in Spring. Spring @Component, @Repository, @Service and @Controller are Stereotype Annotations. @Component is generic stereotype annotation for any Spring-managed component. In the previous version Spring 2.0 introduce the first Stereotype Annotations name as @Repository. The @Component annotations introduced in Spring 2.5 are really just a continuation of the “stereotype” annotations introduced in Spring 2.0. Stereotype annotations are markers for any class that fulfills a role within an application. This helps remove, or at least greatly reduce, the Spring XML configuration required for these components.

These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration(spring.xml).

The Four Types of Spring Stereotype Components and Their Purposes:
+------------+-----------------------------------------------------+
| Annotation | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |
+------------+-----------------------------------------------------+

Target:

          Class
Description:

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

@Component
public class Circle
{
    private Point center;
    ----
}

Annotation @Repository:

Target:

          Class
Description:
In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.
A class that serves in the persistence layer of the application as a data access object (DAO), otherwise known as a repository in some other technologies. Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
@Repository
public class CircleDaoImpl implements CircleDao
{
    private Point center;
    ----
}

Annotation @Service:

Target:

          Class
Description:
Annotate all your service classes with @Service. All your business logic should be in Service classes.
@Service
public class CircleServiceImpl implements CircleService
{
    private Point center;
    ----
}

Annotation @Controller:

Target:

          Class
Description:
The @Controller is a class level annotation, which indicates that the annotated class is a Spring component of type “controller“.
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to. In Spring MVC you can make controller class very easily by prefixing @Controller before any class declaration.
@Controller
public class CircleController
{
    private Point center;
    ----
}

Enable component scanning
Spring by default does not scan means Spring container does create bean for those classes whose annotated with above for stereotype annotations. So we have to enable component scanning explicity by using “context:component-scan” tag in your applicationContext.xml file. So stereotype annotations will be scanned and configured only when they are scanned by DI container of spring framework.

<context:component-scan base-package="com.dineshonjava.app.service" />
<context:component-scan base-package="com.dineshonjava.app.dao" />
<context:component-scan base-package="com.dineshonjava.app.controller" />

The context:component-scan element requires a base-package attribute, the value of base-package attribute should specifies a starting point for a recursive component search. Spring recommends do not use your top package for scanning, so you should declare specific component-scan elements.

Note: If you are using component-scan property for context namespace then you no longer need to declare context:annotation-config, because autowiring is implicitly enabled when component scanning is enabled.

Where to use stereotype annotations?
Always use these annotations over concrete classes; not over interfaces.

  • @Controller annotation is for a class as a Spring Web MVC controller. It is a meta annotation of @Component, so beans annotated with it are automatically imported into the Spring container. If you add the @Controller annotation to a class then you can use handler mappling annotation i.e. @RequestMapping; to map URLs to instance methods of a class.
  • @Service annotation is for a class as a Service of application.
  • @Repository annotation is more suitable annotation that provides additional benefits specifically for DAOs. The @Repository annotation is a meta annotation of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions eligible for translation into Spring DataAccessException.
  • @Component should be used when your class does not fall into either of three categories i.e. Controllers, Services and DAOs.
Spring Related Topics you may like
  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago