何时使用 Spring 的 @Repository 注解?

and*_*ero 3 autowired spring-annotations spring-repositories

在阅读有关在 Spring 中创建自定义查询的信息时,我注意到没有任何类 ( UserRepositoryCustom, UserRepositoryCustomImpl, UserRepository) 使用该@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这就引出了一个问题:什么时候应该使用注释?以及Spring 的组件扫描如何自动检测到未注释的类?

Ram*_*y P 5

它为所有用 @Repository 注释的 bean 激活持久性异常转换,让 JPA 持久性提供程序抛出的异常转换为 Spring 的 DataAccessException 层次结构。

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

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


bal*_*ag3 1

扩展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