本人在网上找了很多的关于SpringMvc整合的Swagger博客,但是按照操作或多或少出现一些问题,以下是本人SpringMVC真个好Swagger的具体步骤。
我的整合分为5个步骤,废话不多少,现在开始进入正题。
(1)导入swagger所需要的jar
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
(2)Jackson所需的jar包
com.fasterxml.jackson.core
jackson-core
2.9.4
com.fasterxml.jackson.core
jackson-databind
2.9.4
com.fasterxml.jackson.core
jackson-annotations
2.9.4
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Description TODO
* @author:jeff
* @date 2018/9/13 16:11
* @Version 1.0
*/
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.a*.b*.controller"))//你的包
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("对外开放接口API文档")
.description("HTTP对外开放接口")
.version("1.0.0")
.termsOfServiceUrl("http://xxx.xxx.com")
.license("LICENSE")
.licenseUrl("http://xxx.xxx.com")
.build();
}
}
@Api()
用于类:表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
@ApiOperation() 用于方法:表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
@ApiOperation(value="登录接口", notes="登录接口")
@RequestMapping(value = "/test",method = {RequestMethod.POST})
@ResponseBody
public BaseResponse test(@ApiParam(name = "userName",value = "用户名",required = true)@RequestParam(value = "userName",required = true)String userName,
@ApiParam(name = "passWord",value = "密码",required = true)@RequestParam("passWord")String passWord,
HttpServletRequest request, HttpServletResponse response){
BaseResponse resp = new BaseResponse<>();
logger.info("用户名:"+userName+" 密码:"+passWord);
resp.setData("{'userName':"+userName+",'passWord':"+passWord+"}");
return resp;
}
@ApiModel()用于类 :表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
@ApiModelProperty()用于方法,字段: 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
例如:
@ApiModel(value = "用户查询返回信息")
public class UserInfoResp {
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "性别")
private String sex;
}
http://{ip}:{port}/{projectName}/swagger-ui.html
projectName为你的项目名