1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
2、swagger类的编写
/**
* Created by wanglu no 2018/4/4 .
*/
@Configuration //让spring加载该类
@EnableSwagger2 //启动swagger
@ConditionalOnProperty(value="swagger.enable",havingValue="true",matchIfMissing=false)
//这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,
其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,
则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。
public class Swagger2 {
@Value("${swagger.enable:false}")
//可以获取属性文件中对应的值(如果属性文件中没有这个属性,则会报错。可以通过赋予默认值解决这个问题
private boolean enableSwagger;
@Value("${swagger.basePackage:cn.com.aaa.finance.controller}")
//可以获取属性文件中对应的值(如果属性文件中没有这个属性,则会报错。可以通过赋予默认值解决这个问题
private String basePackage;
@Bean
public Docket createRestApi() {// 创建API基本信息
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(enableSwagger)
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示
return new ApiInfoBuilder()
.title("金融保险端口")// API 标题
.description("维护在springboot中的api")// API描述
.contact("wanglu")// 联系人
.version("1.0")// 版本号
.build();
}
}
3、接口响应实体对象(注意的问题,一个项目中ApiModel 的value值不能相同,否则生成的swagger显示的字段会被同名的实体类的字段所覆盖)
@ApiModel(value = "录单信息")
public class AccountInfoAPIDto {
@ApiModelProperty(value = "录单人")
private String inputBy;
@ApiModelProperty(value = "录单人名称")
private String inputName;
@ApiModelProperty(value = "车商|合作网点编 码")
private String dealerCode;
@ApiModelProperty(value = "车商|合作网点名 称")
private String dealerName;
@ApiModelProperty(value = "代理人编码")
private String agentCode;
@ApiModelProperty(value = "代理人名称")
private String agentName;
4、post请求接受参数
@ApiOperation(value = "信息录入接口")
@Override
public ResponseDto submitApply(@ApiParam @RequestBody SubmitApplyRequestDto submitApplyRequestDto) {
}
5、get请求接受参数
@ApiOperation(value="发送短信获取验证码")
@ApiImplicitParams({
@ApiImplicitParam(name = "flowid", value = "流程号", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "String")
})
@Override
public ResponseDto applyVerifyCode(String flowId,String userId) {
}
6、完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html