Search code examples
springspring-bootcomponent-scan

SpringBoot do not scan named packages


I build a demo module based on SpringBoot , and include server and client application. The path like:

├── test
│   ├── client
│   │   ├── DemoController.java
│   │   └── ClientApplication.java
│   ├── server
│   │   └── ServerApplication.java

I wrote two conflicting custom annotation @Client and @Server presented on ClientApplication.java and ServerApplication.java.

When I run client or server, the two annotations conflicted.

I want to run ClientApplication without scan package test.server, also for ServerApplication.

I have tried something but not work(springBootVersion = '1.5.11.RELEASE'):

@Client
@SpringBootApplication
@ComponentScan(basePackages = "test.client", excludeFilters = {
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = "test\\.server\\.*"),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, pattern = ServerApplication.class)
})
public class ClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class, args).stop();
    }
}

I wrote the wrong code in ClientApplication.main:

SpringApplication.run(***ServerApplication***.class, args).stop();


Solution

  • For server:

     @ComponentScan(basePackages = "test.server", excludeFilters = {
        @Filter(type = FilterType.REGEX, pattern = "test.client.*")})
    

    For client:

     @ComponentScan(basePackages = "test.client", excludeFilters = {
        @Filter(type = FilterType.REGEX, pattern = "test.server.*")})
    

    Or exclude class using specific filter:

     @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ServerApplication.class)