在实际开发过程中,前后端分离后,那么势必存在如何在多人协作中共享和及时更新API开发接口文档的问题,维护接口文档就变成了必不可少的工作,在初期开发的时候接口一直处在变化中,每次接口更新,都要去单独维护接口文档,做过的老铁都知道这是一件多么令人脑瓜子疼得事。使用swagger2集成文档,有多个优势:
首先是创建一个Spring Boot项目,引入web依赖,引入swagger2相关的依赖,如下:
web依赖
org.springframework.boot
spring-boot-starter-web
swagger2依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
添加一个swagger2 配置类,在项目下新建 config 包并添加一个 Swagger2Config 配置类。
Swagger2Config.java:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger2")
.version("1.0")
.contact(new Contact("demo","demo","demo"))
.build());
}
}
运行项目,输入http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:
swagger 通过注解接口生成文档,包括接口名,请求方法,参数,返回信息等。
@Api: 修饰整个类,用于controller类上
@ApiOperation: 描述一个接口,用户controller方法上
@ApiParam: 单个参数描述
@ApiModel: 用来对象接收参数,即返回对象
@ApiModelProperty: 对象接收参数时,描述对象的字段
@ApiResponse: Http响应其中的描述,在ApiResonse中
@ApiResponses: Http响应所有的描述,用在
@ApiIgnore: 忽略这个API
@ApiImplicitParam: 一个请求参数
@ApiImplicitParam: 多个请求参数
更多使用说明,参考 Swagger 使用手册。
添加一个控制器,在项目下新建 controller包并添加一个 UserController控制器。
UserController.java:
package com.example.demo.controller;
import com.example.demo.entity.Response;
import com.example.demo.entity.ResponseResult;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/* 类注解 */
@Api(value = "用户信息")
@RestController
public class UserController {
@Autowired
UserService service;
/* 方法注解 */
@ApiOperation(value = "获取用户信息")
@RequestMapping(value = "/getUserItem",method = RequestMethod.GET)
public ResponseResult getUserItem(){
try {
User user = service.getUserInfo();
String[] arr= new String[]{"测试"};
return Response.makeOKRsp(user);
}catch (Exception e)
{
return Response.makeErrRsp("查询用户信息异常");
}
}
@ApiOperation("根据id查询用户的接口")
/* 参数注解 */
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "00", required = true)
@RequestMapping(value = "/getUserById",method = RequestMethod.GET)
public ResponseResult getUserById(@PathVariable Integer id) {
User user = service.getUserInfo();
return Response.makeOKRsp(user);
}
@ApiOperation(value = "获取用户字符串")
@RequestMapping(value = "/api/getStr",method = RequestMethod.GET)
public String getStr()
{
return service.getStr();
}
}
如果参数是一个对象,或者返回的是对象,注解如下:
User.java:
package com.example.demo.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel
public class User {
@ApiModelProperty(value = "用户名称")
public String name;
@ApiModelProperty(value = "用户密码")
public int password;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getPassword(){
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String toString(){
return "user{name='"+name+"\',"+"password="+password+"}";
}
}
运行项目,查看swagger2文档:http://localhost:8080/swagger-ui.html
在实际项目开发中,比如采取token验证逻辑的往往在接口请求时需要把token也一起传入后端,修改Swagger2Config配置类。
Swagger2Config.java:
package com.example.demo.config;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Config {
private static final String DESCRIPTION = "测试java api";
@Bean
public Docket api(){
//添加head参数start
ParameterBuilder tokenPar = new ParameterBuilder();
List pars = new ArrayList<>();
tokenPar
.name("Content-Type")
.description("请求类型")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.defaultValue("application/json; charset=UTF-8")
.build();
pars.add(tokenPar.build());
//添加head参数end
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
// .paths(PathSelectors.regex("/api/.*"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description(DESCRIPTION)
.version("1.0")
.license("许可证")
.licenseUrl("许可证URL")
.termsOfServiceUrl("服务条款URL")
// 联系人
.contact(new Contact("curtain", "https://blog.csdn.net/qq_27462223", "0000"))
.extensions(Arrays.asList(new StringVendorExtension("VE-Name", "VE-Value")))
.build();
}
private List securitySchemes() {
return Lists.newArrayList(
new ApiKey("Authorization", "Authorization", "header"));
}
private List securityContexts() {
return Lists.newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build()
);
}
List defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(
new SecurityReference("Authorization", authorizationScopes));
}
}
运行项目,查看文档:
如果我们的Spring Boot项目中集成了Spring Security,那么如果不做额外配置,Swagger2文档可能会被拦截,此时只需要在Spring Security的配置类中重写configure方法,添加如下过滤即可:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/swagger-ui.html")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}
到这里Spring Boot 接入swagger2就已经完成了,当然,除了这些之外,还有一些其它的注解,都比较简单,老铁们可以自己摸索下,更多使用说明,参考 Swagger 使用手册。下次再见。
源码:https://github.com/LeeCurtain/demo.git