前言:该博客主要是记录自己学习的过程,方便以后查看,当然也希望能够帮到大家。
说明
- 引Swagger2.9.2,主要用于生成、描述、调用和可视化RESTful风格的web服务的接口文档,方便调试本地接口使用。
- 完整代码地址在结尾!!
第一步,在pom.xml加入依赖,如下
<!-- web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Swagger2 -->
<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>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>2.9.2</version>
</dependency>
第二步,配置application.yml,避免端口冲突
server:
port: 8081
第三步,创建类TestRequest,TestResponse,如下
TestRequest
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Description:
* @Author: jinhaoxun
* @Date: 2020/5/14 9:30 下午
* @Version: 1.0.0
*/
@Data
public class TestRequest {
@ApiModelProperty(required = true, value = "用户id", example = "123")
private String id;
@ApiModelProperty(required = true, value = "用户name", example = "百里玄刺")
private String name;
@ApiModelProperty(required = true, value = "用户age", example = "18")
private int age;
@ApiModelProperty(required = true, value = "用户sex", example = "男")
private String sex;
}
TestResponse
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Description:
* @Author: jinhaoxun
* @Date: 2020/5/14 9:30 下午
* @Version: 1.0.0
*/
@ApiModel("getTest响应实体")
@Data
public class TestResponse {
@ApiModelProperty(required = true, value = "用户id", example = "123")
private String id;
@ApiModelProperty(required = true, value = "用户name", example = "百里玄刺")
private String name;
@ApiModelProperty(required = true, value = "用户age", example = "18")
private int age;
@ApiModelProperty(required = true, value = "用户sex", example = "男")
private String sex;
}
第四步,创建类Test1Controller,Test2Controller,Test3Controller(在接口上添加对应注解,本人只添加基本的注解),并分别放于com.luoyu.swagger.controller.test1,com.luoyu.swagger.controller.test2,com.luoyu.swagger.controller.test3包下(配置文件里面配置的扫描路径)。
Test1Controller
import com.luoyu.swagger.entity.request.TestRequest;
import com.luoyu.swagger.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test1")
@Api(value = "Test1Controller", tags = "Test1Controller接口")
public class Test1Controller {
/**
* @author jinhaoxun
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
/**
* @author jinhaoxun
* @description 测试接口2
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest2", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test2接口名称", notes = "test2接口描述")
public TestResponse getTest2(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
Test2Controller
import com.luoyu.swagger.entity.request.TestRequest;
import com.luoyu.swagger.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test2")
@Api(value = "Test2Controller", tags = "Test2Controller接口")
public class Test2Controller {
/**
* @author jinhaoxun
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
Test3Controller
import com.luoyu.swagger.entity.request.TestRequest;
import com.luoyu.swagger.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author jinhaoxun
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test3")
@Api(value = "Test3Controller", tags = "Test3Controller接口")
public class Test3Controller {
/**
* @author jinhaoxun
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
第五步,创建Swagger2Config配置文件,如下
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @version 1.0
* @author jinhaoxun
* @date 2019-08-09
* @description Swagger配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 定义分隔符
*/
private static final String SPLITOR = ";";
/**
* @author jinhaoxun
* @description 配置token,以及设置扫描包的路径
* @return Docket
*/
@Bean("createRestApi1")
public Docket createRestApi1() {
//设置header里面的token
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.groupName("1.0.0 版本")
.select()
//此处添加需要扫描接口的包路径
.apis(basePackage("com.luoyu.swagger.controller.test1" + SPLITOR
+ "com.luoyu.swagger.controller.test2" + SPLITOR ))
.paths(PathSelectors.any())
.build();
}
/**
* @author jinhaoxun
* @description 配置token,以及设置扫描包的路径
* @return Docket
*/
@Bean("createRestApi2")
public Docket createRestApi2() {
//设置header里面的token
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.groupName("2.0.0 版本")
.select()
//此处添加需要扫描接口的包路径
.apis(basePackage("com.luoyu.swagger.controller.test3" + SPLITOR ))
.paths(PathSelectors.any())
.build();
}
/**
* @author jinhaoxun
* @description 配置Swagger2页面显示内容
* @return Docket
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger 接口文档")
.description("Swagger 接口文档")
.version("1.0.0")
.termsOfServiceUrl("http://localhost:8081/swagger-ui.html")
.contact("luoyu")
.build();
}
/**
* @author jinhaoxun
* @description 重写basePackage方法,使能够实现多包访问
* @param basePackage 所有包路径
* @return Predicate<RequestHandler>
*/
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return input -> declaringClass(input).map(handlerPackage(basePackage)::apply).orElse(true);
}
/**
* @author jinhaoxun
* @description 重写basePackage方法,使能够实现多包访问
* @param basePackage 所有包路径
* @return Function<Class<?>, Boolean>
*/
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return input -> {
// 循环判断匹配
for (String strPackage : basePackage.split(SPLITOR)) {
assert input != null;
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
};
}
/**
* @author jinhaoxun
* @description 重写basePackage方法,使能够实现多包访问
* @param input
* @return Optional<? extends Class<?>>
*/
private static Optional<Class<?>> declaringClass(RequestHandler input) {
return Optional.ofNullable(input.declaringClass());
}
}
说明:
- @Configuration 标识这是一个配置类
- @EnableSwagger2 开启swagger2
第六步,启动项目,访问:http://localhost:8081/swagger-ui.html,端口号根据配置文件application.yml里面的端口号进行修改,使用结果如下图
1589098844372.jpg另外,此处提供一些常用注解。如下
@Api() 用于类;表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
@ApiIgnore
作用于方法上,使用这个注解swagger将忽略这个接口
完整代码地址:https://github.com/Jinhx128/springboot-demo
注:此工程包含多个module,本文所用代码均在swagger-demo模块下
后记:本次分享到此结束,本人水平有限,难免有错误或遗漏之处,望大家指正和谅解,欢迎评论留言。
网友评论