Introduction:

In this tutorial, you will learn the different Spring stereotype annotations (@Component, @Repository and @Service) to declare any class as a Spring-managed Bean. Spring MVC also has several other annotations like @Controller and @RestController. The classes that are managed as beans in Spring are known as Managed Components.

There are basically few stereotype annotations in spring that declare classes as Managed Components.

  • The @Component annotation declares any class as a managed spring bean.
  • The @Service annotation declares any Service/Business layer class as a managed component.
  • Similarly, the @Repository annotation declares any DTO or Repository class as a managed bean.
  • In Spring MVC, @Controller and @RestController are used to declare Controllers for the presentation layer.

Related articles:

Why use Stereotype annotations?

Stereotypes annotations denote the roles of types or methods in the overall architecture (at a conceptual, rather than implementation, level). Intended for use by tools and aspects (making an ideal target for pointcuts).

Stereotype annotation distinguishes the classes from the architecture prospective, it has nothing to do with the actual implementations inside.

How to use the annotations?

Step-1
The simple way to use these annotations is first annotating the @Configuration class with @ComponentScan annotation and specify the package/base-package in which the classes present. For more information, check the related article Classpath Scanning using @ComponentScan and Filters.

Java
@Configuration
@ComponentScan("com.jbd.webapp")
public class AppConfig {
  //Extra config goes
}

Step-2
Next step is to annotate the classes with respective annotations.

Java
package com.jbd.webapp;

@Repository
public class AppRepository {
  //...
}

Differences between @Component, @Repository, @Service

1. The @Component annotation

We can use @Component annotation in our application to declare any class as the Spring’s managed components. Spring internally picks up and registers beans with @Component and doesn’t look for @Service and @Repository in general. Because the @Service and @Repository are also annotated with @Component.

  • The @Component annotation is a generic stereotype annotation used to designate any Spring-managed component.
  • It indicates that the annotated class is a candidate for auto-detection and bean registration during the component scanning process.
  • It’s a general-purpose annotation and can be used to annotate any class that should be managed by the Spring container.

In simple words, the classes under the @ComponentScan path annotated with @Component annotation will be registered as a Bean in Spring ApplicationContext. You can use the instance of such bean using the @Inject or @Autowired annotations.

Java
@Component
public class PdfReader {
  //class members
}

As you can see in the below, @Component annotation accepts optional component name as the parameter.

Java
@Target(ElementType.TYPE) // Can be used on Class, Interface and Enum
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	String value() default "";
}

2. The @Service annotation

  • The @Service annotation is also a specialization of @Component and is used to annotate classes that perform a specific service or business logic.
  • It indicates that the annotated class is a service component, responsible for implementing business logic or coordinating the application’s workflow.
  • It’s commonly used in service layer classes within the application.

Any class that includes business logic is annotated with @Service annotation. Just like the @Component, all you need is to annotate the class with @Service("optionalName") with an optional name.

Java
@Service("orderService")
public class OrderService {
  //Class details
}

The @Service annotation internally looks as below. It is clear that this annotation is just an alias of @Component. It just does not have any other special feature till now.

Java
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";
}

3. The @Repository annotation

  • The @Repository annotation is a specialization of @Component and is used to annotate classes that serve as data access objects (DAOs) or repositories.
  • It indicates that the annotated class is a repository, typically responsible for encapsulating data access logic such as CRUD operations on a database.
  • It’s often used in combination with Spring’s data access technologies like Spring Data JPA or Spring JDBC.

Any class that holds the database or persistent logic is annotated with @Repository. In other words, the DTO/DAO is annotated with @Repository with an optional name parameter.

Java
@Repository
public class OrderDaoImpl implements OrderDao {
  //Order manipulation methods.
}

As you can see this annotation is just an alias of @Component. Remember, @Repository catches persistence specific checked exceptions and rethrow them as one of Spring’s unified unchecked exception.

Java
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";
}

Conclusion:

I hope you learned to manage beans in Spring using different annotations like @Component, @Service, and @Repository. In short, the @Component annotation is used to declare any general class as a Spring-managed bean class, @Service is used to declare any class as a Business logic (Service) class and @Repository is for the DTO, DAO, or repository class where the database operations are performed. This also demonstartes about @Componet vs. @Repository and @Service. While @Component is a generic stereotype annotation, @Repository and @Service are more specific stereotypes used to annotate classes with well-defined roles within a Spring application. Choosing the appropriate annotation helps to convey the intended purpose of the annotated class and provides additional metadata for Spring’s component scanning and auto-wiring mechanisms.

By |Last Updated: April 2nd, 2024|Categories: Spring Framework|