使用 Spring Data Rest 时如何从组件扫描中排除 @Repository

How to exclude a @Repository from component scan when using Spring Data Rest

在 spring 引导项目中,我无法从组件扫描中排除一些存储库。

我有一个包含一些实体和一些存储库 (JpaRepositories) 的库。出于某种原因,我实现了一个小型 Spring Boot Data Rest 应用程序,该应用程序将用于让测试人员快速访问实体。因此,我实现了一个扩展 PagingAndSortingRepository 并使用 @RepositoryRestResource 注释的存储库。

当应用程序启动时,将扫描所有存储库并使其可用。只要我只想让 Data Rest 存储库可用,我就注释了 componenten 扫描器以排除不需要的存储库。但这不起作用。我检查了执行器 bean 端点以及我所做的一切 - 没有存储库被排除在外。

为了演示这个问题,我创建了一个简单的演示应用程序:https://github.com/magomi/springboot-restdata-repoloading

为了排除 DataRepository,我尝试了两种方法:

// exclude V02
@SpringBootApplication
@ComponentScan(excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
                DataRepository.class})
})

// exclude V01
@SpringBootApplication(exclude = { DataRepository.class })

没有成功。当我调用 /beans 端点(由 spring 引导执行器提供)时,我总是看到

{
    bean: "dataRepository",
    aliases: [ ],
    scope: "singleton",
    type: "org.codefromhell.test.repoloading.DataRepository",
    ...
},
{
    bean: "dataApiRepository",
    aliases: [ ],
    scope: "singleton",
    type: "org.codefromhell.test.repoloading.api.DataApiRepository",
    ...
},

因为它是一个存储库而不是严格意义上的 @Component,您需要通过将 @EnableJpaRepositories 添加到您的应用程序来排除它:

@SpringBootApplication
@EnableJpaRepositories(excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {
                DataRepository.class})
})
public class ApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}

您可以在存储库界面上使用 org.springframework.data.repository.NoRepositoryBean 注释。 来自文档:

Annotation to exclude repository interfaces from being picked up and thus in consequence getting an instance being created.

This will typically be used when providing an extended base interface for all repositories in combination with a custom repository base class to implement methods declared in that intermediate interface. In this case you typically derive your concrete repository interfaces from the intermediate one but don't want to create a Spring bean for the intermediate interface.