Anton Kim
Anton Kim

Reputation: 953

Spring - @Repository annotation in service class

What is the point of putting @Repository in service class CustomerServiceImpl and is it a good practice in this example, my understanding it is not needed for any interfaces that extend JpaRepository and exception translation already included. As far as I understand @Repository "should" be on repository class?

@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {

  @PersistenceContext
  private EntityManager em;

  @Autowired
  private CustomerRepository repository;
  ...
}



@Transactional(readOnly = true)
public interface CustomerRepository extends JpaRepository<Customer, Long> {}

Upvotes: 0

Views: 153

Answers (1)

Gopinath
Gopinath

Reputation: 4967

Technically, the @Repository annotation may not be absolutely necessary in the given example for the CustomerServiceImpl class.

However, the use of @Repository annotation optimizes the 'search' and 'List all' operations by implementing the 'Domain Driven Design' pattern.

Example: The underlying repository can be a Relational database / No-sql database / a CSV file. Use of @Repository will hide the implementation complexity from 'Search' and 'List all' operations in this case.

Upvotes: 1

Related Questions