用swagger为springboot生成接口文档

一、为什么要用swagger,它解决了什么问题?

  随着sprnigboot、springc loud等微服务的流行,在微服务的设计下,小公司微服务小的几十,大公司大的几百上万的微服务。这么多的微服务必定产生了大量的接口调用。而接口的调用就必定要写接口文档。在微服务的盛行下,成千上万的接口文档编写,不可能靠人力来编写,故swagger就产生了,它采用自动化实现并解决了人力编写接口文档的问题。它通过在接口及实体.上添加几个注解的方式就能在项目启动后自动化生成接口文档。

  Swagger提供了一个全新的维护API文档的方式,有4大优点:
1.自动生成文档:只需要少量的注解,Swagger 就可以根据代码自动生成API文档,很好的保证了文档的时效性。
2.跨语言性,支持40多种语言。
3. Swagger UI呈现出来的是一份可交互式的API 文档,我们可以直接在文档页面尝试API的调用,省去了准备复杂的调用参数的过程。
4.还可以将文档规范导入相关的工具(例如SoapUI) ,这些工具将会为我们自动地创建自动化测试。

二、把springboot的接口,自动生成接口文档

1.配置依赖包pom.xml文件

<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- Swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

2.修改配置文件application.properties

#表示是否开启swagger,一般线上环境是关闭的
spring.swagger2.enabled=true

3.增加一个swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Value(value = "${spring.swagger2.enabled}")
private Boolean swaggerEnabled;

@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(swaggerEnabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.guo.boot"))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("swagger 接口文档")
.termsOfServiceUrl("https://wwww.baidu.com")
.version("1.0")
.build();
}
}

以上注意点:

createRestApi()这个方法一定要写上你的包名,代表需要生成接口文档的目录包。

体验地址:http://127.0.0.1:8888/swagger-ui.html

三、案例

扫描二维码关注公众号,回复: 10296011 查看本文章

controller

@Api(description = "用户接口")
@RestController
@RequestMapping("/user")
public class UserController {

@ApiOperation("修改某条数据")

@GetMapping(value = "/u/{id}")
public UserVO findById(@PathVariable int id){
Random rand = new Random();
UserVO user = new UserVO();
user.setId(id);
String temp = "temp01";
user.setUsername(temp);
user.setPassword(temp);
int n = rand.nextInt(2);
user.setSex((byte)n);
return user;

}
@ApiOperation("单个用户查询,按userid查用户信息")
@PostMapping(value = "/user/create",produces = {"application/json;charset=UTF-8"},consumes ={"application/json;charset=UTF-8"})
public UserVO createrUser(@RequestBody UserVO userVO ) {return userVO;}

}

bean

@Api(value = "用户信息")
@Data
public class UserVO {
@ApiModelProperty(value = "用户id")
private Integer id;

@ApiModelProperty(value = "用户名")
private String username;

@ApiModelProperty(value = "密码")
private String password;

@ApiModelProperty(value = "性别 0=女 1=男")
private Byte sex;

@ApiModelProperty(value = "删除标志,默认0不删除,1删除")
private Byte deleted;

@ApiModelProperty(value = "更新时间")
private Data updateTime;
}

常用注解:

swagger常用注解
注解 用途 注解位置
@Api 描述类的作用 注解于类上
@ApiOperation 描述类的方法的作用 注解于方法上
@ApiParam 描述类方法参数的作用 注解于方法的参数上
@ApiModel 描述对象的作用 注解于请求对象或者返回结果对象上
@ApiModelPropert 描述对象里字段的作用 注解于请求对象或者返回结果对象里的字段上

猜你喜欢

转载自www.cnblogs.com/97guoxiang/p/12595793.html