autowired – When to use Springs @Repository annotation?

autowired – When to use Springs @Repository annotation?

It activates persistence exception translation for all beans annotated with @Repository, to let exceptions being thrown by the JPA persistence providers be converted into Spring’s DataAccessException hierarchy.

That Means all un checked exceptions thrown in that class will be converted to DataAccessException.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.create-instances

@Autowired asks the Spring IoC-Container for an object of type AddressRepository.
Being an interface, it cant be instantiated, therefore there has to be an implementation.

org.springframework.data.jpa.repository.support.SimpleJpaRepository is that implementation:

@Repository
@Transactional(readOnly = true)
public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T, ID> {

and here you see the @Repository annotation, which acts as a specialization for @Component.

autowired – When to use Springs @Repository annotation?

Extending org.springframework.data.repository.Repository interface marks the subclasses for bean creation.
In your case the inheritance looks the following:
YourRepository -> JpaRepository -> PagingAndSortingRepository -> CrudRepository -> org.springframework.data.repository.Repository
According the documentation:
General purpose is to hold type information as well as being able to discover interfaces that extend this one during classpath scanning for easy Spring bean creation.
Source: Interface Repository

Leave a Reply

Your email address will not be published. Required fields are marked *