2、Swagger
1、前言
很多人员会抱怨别人写的接口文档不规范,不及时更新。但是当自己写的时候确实最烦去写接口文档。这种痛苦只有亲身经历才会牢记于心。
如果接口文档可以实时动态生成就不会出现上面问题。
Swagger可以完美的解决上面的问题。
2、开发
①、添加jar依赖
springboot starter 依赖版本控制在2.5.6下。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
②、添加注解
在SpringBoot的启动类中添加@EnableSwagger2注解。
@SpringBootApplication
@EnableSwagger2
public class MyApp {
public static void main(String [] args){
SpringApplication.run(MyApp.class,args);
}
}
启动项目后在浏览器中输入http://ip:port/swagger-ui.html即可以访问到swagger-ui页面,在页面中可以可视化的进行操作项目中所有接口。
访问swagger-ui.html后可以在页面中看到所有需要生成接口文档的控制器名称。

@Configuration
public class SwaggerConfig {
@Bean
public Docket getDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(swaggerDemoApiInfo())
.select()
.build();
}
private ApiInfo swaggerDemoApiInfo(){
return new ApiInfoBuilder()
.contact(new Contact("文档名字", "http://www.bjsxt.com", "xxx@163.com"))
//文档标题
.title("这里是Swagger的标题")
//文档描述
.description("这里是Swagger的描述")
//文档版本
.version("1.0.0")
.build();
}
}
1、@Api是类上注解。
控制整个类生成接口信息的内容。
@Api(tags = {"mydemo"},description = "描述")
对方法进行总体描述。
@ApiOperation(value="接口描述",notes = "接口提示信息")
3、@ApiParam是在方法参数前面。
用于对参数进行描述或说明是否为必添项等说明
public People getPeople(Integer id, @ApiParam(value="姓名",required = true) String name, String address)
@ApiModel(value = "人类",description = "描述")
public class People { ...}
5、@ApiModelProperty是用属性上。
用于当对象作为参数时定义这个字段的内容。
@ApiModelProperty(value = "姓名",name = "name",required = true,example = "张三")
private String name;
或者
@ApiModelProperty(value = "姓名")
private String name;

浙公网安备 33010602011771号