SpringBoot2.6.13版本引入Swagger

天门道人發表於2024-07-11

1.引入依賴

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

2.配置類

 1 @Configuration
 2 @EnableSwagger2
 3 public class SwaggerConfig implements WebMvcConfigurer {
 4 
 5     @Value("${springfox.documentation.enabled:false}")
 6     private boolean enabled;
 7 
 8     @Bean
 9     public Docket api() {
10         return new Docket(DocumentationType.SWAGGER_2)
11                 .enable(enabled)
12                 .apiInfo(apiInfo())
13                 .select()
14                  //替換為你的控制器包路徑
15                 .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
16                 .paths(PathSelectors.any())
17                 .build();
18     }
19 
20 
21     private ApiInfo apiInfo() {
22         return new ApiInfoBuilder()
23                 .license("yibing")
24                 .title("xx系統API文件")
25                 .description("測試系統")
26                 .version("1.0")
27                 .build();
28     }
29 }

3. Controller註解

 1 @Slf4j
 2 @RestController
 3 @RequestMapping("/log")
 4 @Api(tags = "日誌管理")
 5 public class LogController {
 6 
 7     @ApiOperation("鏈路追蹤")
 8     @PostMapping("/trace")
 9     public TraceResponse log(@RequestBody @Validated TraceReq req) {
10         log.info("console log");
11         log.info("stop");
12         return new TraceResponse();
13     }
14 }

4.入參

@Data //必須要有,否則swagger不能讀取屬性
@ApiModel("鏈路追蹤請求")
public class TraceReq {
    @ApiModelProperty(notes = "id", required = true)
    private String id;
}

5.出參

@Data
@ApiModel("鏈路追蹤響應")
@AllArgsConstructor
public class TraceResponse {
    @ApiModelProperty(notes = "資料字串", required = true)
    private String data;
}

6.配置項

#swagger啟用開關
springfox.documentation.enabled=true


#Spring Boot 2.6.0 及以後版本中引入的一個配置屬性,用於控制 Spring MVC 中的路徑匹配策略
#這個配置的引入主要是為了解決一些向後相容性問題,特別是與一些第三方庫(如 Springfox Swagger)的相容性問題
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

7.訪問UI頁面

http://xxx:8080/doc.html

相關文章