Swagger如何匹配多個Controller類或者目錄


提示:方法四或許是你們需要的方法!!!

 

方法一(最普通的方式):匹配一個controller目錄下的所有controller類。

  

 1  @Bean
 2     public Docket creatRestApi(){
 3         return new Docket(DocumentationType.SWAGGER_2)
 4                 .apiInfo(apiInfo())
 5                 .select()
 6                 //關鍵語句
 7                 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")
 8                 )
 9                 .paths(PathSelectors.any())
10                 .build();
11     }

 

方法二匹配有指定注解的類。

 1  @Bean
 2     public Docket creatRestApi(){
 3         return new Docket(DocumentationType.SWAGGER_2)
 4                 .apiInfo(apiInfo())
 5                 .select()
 6                 //關鍵語句
 7                 .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)
 8                 )
 9                 .paths(PathSelectors.any())
10                 .build();
11     }

 

方法三匹配有指定注解的方法。

 1 @Bean
 2     public Docket creatRestApi(){
 3         return new Docket(DocumentationType.SWAGGER_2)
 4                 .apiInfo(apiInfo())
 5                 .select()
 6                 //關鍵語句
 7                 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)
 8                 )
 9                 .paths(PathSelectors.any())
10                 .build();
11     }

 

方法四我覺得是最重要的方法(強烈推薦!!!!):可以匹配多個controller包(多個controller包不在同一級)

             

 1  @Bean
 2     public Docket creatRestApi(){
 3         return new Docket(DocumentationType.SWAGGER_2)
 4                 .apiInfo(apiInfo())
 5                 .select()
 6                 .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.example.demo.controller"),
 7                         RequestHandlerSelectors.basePackage("com.example.demo.gp.controller"),
 8                         RequestHandlerSelectors.basePackage("com.gp.callback.controller"))
 9                 )
10                 .paths(PathSelectors.any())
11                 .build();
12         
13     }

 如果上面的Predicates類報紅的話,pom文件導入jar包

 <!-- guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>

 

總結:相比四種方法,如果項目中只有一個controller包的話,直接使用方法一就可以了,如果項目中有多個controller包,那么我建議使用方法四。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM