Java 后端整合 Swagger + Knife4j 接口文档
官方文档: https://doc.xiaominfo.com/docs/quick-start
1.引入依赖
1 2 3 4 5 6 7
| <!--引入Knife4j的官方start包,Swagger2基于Springfox2.10.5项目--> <dependency> <groupId>com.github.xiaoymin</groupId> <!--使用Swagger2--> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.9</version> </dependency>
|
2.添加配置类,注意:basePackage 需要填写 controller 的路径
千万注意:线上环境不要把接口暴露出去!!!可以通过在 SwaggerConfig 配置文件开头加上 @Profile({"dev", "test"})
限定配置仅在部分环境开启
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Configuration @EnableSwagger2WebMvc @Profile({"dev","test"}) public class Knife4jConfiguration {
@Bean(value = "dockerBean") public Docket dockerBean() { Docket docket=new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .description("# Knife4j RESTful APIs") .termsOfServiceUrl("https://doc.xiaominfo.com/") .contact("xiaoymin@foxmail.com") .version("1.0") .build()) .groupName("用户服务") .select() .apis(RequestHandlerSelectors.basePackage("com.yupi.yupao.controller")) .paths(PathSelectors.any()) .build(); return docket; } }
|
如果开发者使用的是Knife4j 2.x版本,并且Spring Boot版本高于2.4,那么需要在Spring Boot的yml文件中做如下配置:
3.在 application.yml 中
1 2 3 4 5
| spring: mvc: pathmatch: # 配置策略 matching-strategy: ant-path-matcher
|
4.controller类中备注接口相应的信息
1 2 3 4 5 6 7 8 9 10 11
| @Api(tags = "首页模块") @RestController public class IndexController {
@ApiImplicitParam(name = "name",value = "姓名",required = true) @ApiOperation(value = "向客人问好") @GetMapping("/sayHi") public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){ return ResponseEntity.ok("Hi:"+name); } }
|
5.访问地址,注意端口、实际的地址
端口对应,正常访问http://localhost:8080/doc.html
如果配置类当中有配置路径,则需要加上
1 2 3 4
| server: port: 8888 servlet: context-path: /api
|
该地址访问:http://localhost:8888/api/doc.html