Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
In Spring and Spring Boot applications, @Service
and @Repository
are both stereotypes, and they provide a way to annotate and define the roles or semantics of classes. Let's delve into their differences:
Primary Purpose:
Exception Translation:
@Repository
annotation, Spring provides a persistence exception translation mechanism. This means that data access exceptions (typically, technology-specific, like SQLException for JDBC) are automatically translated into Spring's DataAccessException hierarchy, making error handling more consistent and easier.Typical Annotations Used With:
@Transactional
. This ensures that methods in the service class participate in a transaction.@Repository
usually work closely with the @Entity
classes in JPA-based applications and often involve @Query
, @Persist
, @Update
, etc.Layering:
Component Scanning:
@Component
annotation. When you use <context:component-scan/>
in XML configuration or @ComponentScan
in Java configuration, Spring will automatically detect and register beans for classes annotated with @Service
or @Repository
.AOP Integration:
@Service
often means it's a likely target for aspects that deal with business operations (like transactions).In summary, while both @Service
and @Repository
help define the semantics and roles of classes in a Spring application, they serve different purposes. @Service
is for business logic, and @Repository
is for data access logic. These annotations, along with @Controller
(for the presentation layer), help define a clear layered architecture for Spring applications.
Transaction management with @Service
and @Repository
in Spring Boot:
@Service
and @Repository
classes can participate in transactions.@Service
):@Service @Transactional public class UserService { // Business logic with transactional support }