0

I have a Spring boot application which has a UserRepository but I have not annotated that repository with @Repository but still my application works fine.

Why @Repository annotation is optional in Spring boot and what is the best practise that should we annotate it or not in repository classes.

Aditya
  • 950
  • 8
  • 37

4 Answers4

0

It is working because spring will scan the class path and identify given class is repository (DAO) based on the imports, when use @Repositary spring context know how to handle expections like re-throw to pre defined methods ..etc, and also this annotation help readability of the code.

rev
  • 77
  • 1
  • 8
0

For @Repository annotation even if you haven't mentioned Spring recognizes the repositories by the fact that they are extending Repository interfaces like JPARepository or CrudRepository.

So, it's not mandatory to mention annotation, you can check in your code whether you have mentioned @EnableJpaRepositories("packages") above Main class or not. That might also be one of the reasons why it is working.

As per best practices for annotations, they have a purpose to fulfill, @Repository is important from a database connection perspective, where it has lots of proper exceptions throw, or pre-defined methods.

If you do not use the proper annotations, you may face commit exceptions overridden by rollback transactions. You will see exceptions during the stress load test that is related to roll-back JDBC transactions.

For more clarity have a look at this post

0

I assume you have somewhere implicitly or explicitly a EnableJpaRepositories annotation which scans all Spring repositories and your repositories are extending CrudRepository or other Spring Data base classes.

The annotation is only needed when defining you own repositories without using Spring Data mechanism. Note, that Repository is just a special Component, latter should also do it to have DI enabled, so this is more for better recognizing the purpose of the class.

k_o_
  • 5,143
  • 1
  • 34
  • 43
0

@Repository is used to indicate interface that extends a jpa repository, for example. Notice in the example below, the interface extends the Beer class and the BeerQueries query interface.

package com.algaworks.brewer.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.algaworks.brewer.model.Beer;
import com.algaworks.brewer.repository.helper.beer.BeersQueries;

@Repository
public interface Beers extends JpaRepository<Beer, Long>, BeersQueries {

}
Elikill58
  • 4,050
  • 24
  • 23
  • 45