什么时候使用Spring的@Repository批注?

时间:2019-04-17 13:26:05

标签: autowired spring-annotations spring-repositories

在阅读有关creating custom queries in Spring的信息时,我注意到没有一个类(UserRepositoryCustomUserRepositoryCustomImplUserRepository)使用@Repository注释。

我对此感到惊讶,因为通常所有Spring应用程序类都用某种注释来进行检测,并为其生成代理。这就是面向方面的框架在Java中的工作方式。

然后,我检查了以前的正在工作的代码,并意识到我的存储库界面也不使用注释。但是,它@Autowired作为对使用它的控制器和其他类的依赖。示例:

// AddressRepository.java
public interface AddressRepository extends CrudRepository<Address, String> {
}

// Repositories.java
@Getter // lombok
@Component
public class Repositories { // autowire this to have access to all repo's
    private final AddressRepository addressRepository;

    @Autowired
    public Repositories(AddressRepository addressRepository) {
        this.addressRepository = addressRepository;
    }
}

这引起了以下问题:何时应使用注释? Spring的组件扫描如何自动检测未注释的类?

3 个答案:

答案 0 :(得分:2)

它为所有使用@Repository注释的bean激活持久性异常转换,以便将JPA持久性提供程序引发的异常转换为Spring的DataAccessException层次结构。

这意味着该类中抛出的所有未经检查的异常都将转换为DataAccessException。

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

答案 1 :(得分:0)

扩展org.springframework.data.repository.Repository接口可标记用于创建bean的子类。
在您的情况下,继承看起来如下:
YourRepository-> JpaRepository-> PagingAndSortingRepository-> CrudRepository-> org.springframework.data.repository.Repository
根据文档:
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.
来源:Interface Repository

答案 2 :(得分:0)

@Autowired向Spring IoC容器询问类型AddressRepository的对象。 作为一个接口,它不能被实例化,因此必须有一个实现。

org.springframework.data.jpa.repository.support.SimpleJpaRepository是该实现:

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

在这里您看到@Repository注释,它是@Component的专门化。