需求:
项目开发都需要在线文档,并且在生产环境关闭接口文档。
项目环境区分可以参考:maven 不同环境灵活构建
项目工程可以参考:我的web Demo
一、框架整合
1. 依赖获取:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
- 自定义
Bean
,区分环境加载 Bean:
/**
* 只有本地开发和测试环境才启用swagger 生产禁止使用
* @author NanNan Wang
*/
@Profile({
"dev","test"})
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean(value = "swaggerBean")
public Docket swaggerBean() {
//指定使用Swagger2规范
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//描述字段支持Markdown语法
.description("# 项目模版dmeo")
.termsOfServiceUrl("https://doc.xiaominfo.com/")
.contact("[email protected]")
.version("1.0")
.build())
//分组名称
.groupName("demo")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.github.nan.web.demos.web"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
- 使用注解
@Api(tags = "请求规范")
@RestController
@RequestMapping("/demos")
public class DemoController {
@ApiOperation(value = "向世界问好")
@GetMapping("/hello")
public String hello() {
return "hello world!";
}
}
- 启动项目查看接口文档
https://localhost:8081/doc.html
二、常用的注解
常用注解如下:
- @Api 定义API的基本信息,如标题、描述等。 在Controller类上使用,指定API的基本信息。
- @ApiOperation 定义API的操作,如GET、POST等。 在Controller方法上使用,指定该方法的操作信息。
- @ApiParam 定义方法参数的信息,如名称、描述等。 在Controller方法的参数上使用,指定参数的信息。
- @ApiModel 定义数据模型的信息。 在DTO类上使用,指定数据模型的信息。
- @ApiModelProperty 定义数据模型属性的信息,如名称、描述等。 在DTO类的属性上使用,指定属性的信息。
- @ApiResponses 定义方法返回的HTTP响应。 在Controller方法上使用,指定方法的返回响应信息。
- @ApiResponse 定义单个HTTP响应的信息。 在@ApiResponses
注解内使用,指定单个HTTP响应的信息。 - @ApiIgnore 忽略该API,不会在文档中显示。 在Controller类或方法上使用,忽略指定的API。
- @ApiImplicitParam 定义方法的参数,如路径参数、请求参数等。 在Controller方法上使用,指定方法的参数信息。
- @ApiImplicitParams 定义多个方法参数。 在Controller方法上使用,指定多个参数的信息。
- @ApiError 定义API可能出现的错误。 在Controller方法上使用,指定可能出现的错误信息。
- @ApiErrors 定义多个API可能出现的错误。 在Controller方法上使用,指定多个可能出现的错误信息。
三、常见问题
3.1 org.springframework.context.ApplicationContextException: Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException
这个错误可能出现在 3.x版本,解决方法是在配置文件中 增加
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
。