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

不羁的心 提交于 2019-12-05 00:10:03

问题


in a spring boot project I have problems to exclude some repositories from the component scan.

I have a library that contains some entities and some repositories (JpaRepositories). For some reason I implemented a small Spring Boot Data Rest application that shall be used to give testers a quick access to the entities. Therefore I implemented a repository that extends the PagingAndSortingRepository and is annotated with @RepositoryRestResource.

When the application starts all repository will be scanned and made available. As long as I only want to have the Data Rest repositories available I annotated the componenten scanner to exclude the unwant repositories. But this doesn't work. I checked with the actuator beans endpoint and whatever I do - no repositories are excluded.

To demonstrate the problem I created a simple demo application: https://github.com/magomi/springboot-restdata-repoloading.

To exclude the DataRepository I tried the two approaches:

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

and

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

Without success. When I call the /beans endpoint (provided by spring boot actuator) I always see

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

回答1:


Because it's a repository and not strictly a @Component, you need to excluded it by adding @EnableJpaRepositories to your application:

@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);
    }
}



回答2:


You can use org.springframework.data.repository.NoRepositoryBean annotation over your repository interface. From doc:

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.



来源:https://stackoverflow.com/questions/41046736/how-to-exclude-a-repository-from-component-scan-when-using-spring-data-rest

工具导航Map