SpringBoot2.6.13版本引入Swagger
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