赞
踩
Swagger依赖信息
<!--接口文档生成工具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> <version2.9.2</version> </dependency> <!—以下两个依赖用于生成文档,自定义注解使用--> <!--实现Swagger导出离线API文档--> <dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup</artifactId> <version>1.3.3</version> <scope>test</scope> </dependency> <!--Swagger 自定义map参数--> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.21.0-GA</version> </dependency>
一、 Swagger基本注解介绍
@EnableSwagger2:放在启动类上或Swagger配置类上。
举例:1
@EnableSwagger2
public class SwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerApplication.class, args);
}
}
举例:2
@Configuration @EnableSwagger2 public class SwaggerConfig { // 定义分隔符,配置Swagger多包 private static final String splitor = ";"; @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2) //将api的元素设置为包含在json resource listing响应中 .apiInfo(buildApiInfo()) //设置ip和端口,或者域名 //.host("127.0.0.1:8080") //选择那些路径和api会生成document .select() //要扫描的API(Controller)基础包(多个包用 ; 隔开) .apis(basePackage("com.erp.user.storage.controller" + splitor + "com.erp.user.preview.controller" + splitor + "com.erp.user.swaggerDemo.controller" )) //错误路径不监控 .paths(Predicates.not(PathSelectors.regex("/error.*"))) //对根下所有路径进行监控 .paths(PathSelectors.any()) .build(); } private ApiInfo buildApiInfo() { return new ApiInfoBuilder() //文档标题 .title("用户服务API") //文档描述 .description("用户服务调试接口文档") //联系人 // .contact(new Contact("name", "url", "email")) //版本号 .version("0.0.1") //更新此API的许可证信息 //.license("Apache 2.0") //更新此API的许可证Url //.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") //更新服务条款URL //.termsOfServiceUrl("NO terms of service") .build(); } /** * @param basePackage * @description 重写basePackage方法,使能够实现多包访问,复制贴上去 * @returen com.google.common.base.Predicate<springfox.documentation.RequestHandler> */ public static Predicate<RequestHandler> basePackage(final String basePackage) { return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true); } private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) { return input -> { // 循环判断匹配 for (String strPackage : basePackage.split(splitor)) { boolean isMatch = input.getPackage().getName().startsWith(strPackage); if (isMatch) { return true; } } return false; }; } private static Optional<? extends Class<?>> declaringClass(RequestHandler input) { return Optional.fromNullable(input.declaringClass()); } }
@Api:放在请求的类上,与 @Controller 并列,说明类的作用,如用户模块,用户类等。
tags="说明该类的作用"
value="该参数没什么意义,所以不需要配置"
description = "用户基本信息操作"
举例:
@Api(value = "用户Controller",tags = "用户信息测试")
@RestController
@RequestMapping("/user")
public class UserController {
//TODO
}
@ApiOperation:"用在请求的方法上,说明方法的作用"
value="说明方法的作用"
notes="方法的备注说明"
tags="说明该方法的作用,参数是个数组,可以填多个"
格式:tags={"作用1","作用2"}
httpMethod="设置显示的请求方式GET、POST、PUT、DELETE"
举例:
@ApiOperation(value = "查询用户信息",notes = "方法的备注说明,如果有可以写在这里",httpMethod = "GET")
@RequestMapping(value = "/findUser")
public User findUser(@RequestParam String userId){
//TODO
}
@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(请求体)--> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType="int"
defaultValue:参数的默认值
举例:多个参数
@ApiOperation(value = "查询用户",notes = "查询用户的所有信息",httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId",value = "用户Id",dataType = "String",paramType = "form",required = true),
@ApiImplicitParam(name = "userName",value = "用户名",dataType = "String",paramType = "form",required = true),
@ApiImplicitParam(name = "password",value = "密码",dataType = "String",paramType = "form",required = true),})
@RequestMapping("/findList")
public List<User> findList(String userId, String userName, String password,Integer age){
//TODO
}
举例:单个参数
@ApiOperation(value = "查询用户信息",notes = "根据id查询用户信息",httpMethod = "GET")
@ApiImplicitParam(name = "userId",value = "用户id",paramType = "query",dataType = "String",example = "根据id查询用户",required = true)
@RequestMapping(value = "/findUser")
public User findUser(@RequestParam String userId){
//TODO
}
@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
举例:
@ApiOperation(value = "修改密码", notes = "方法的备注说明,如果有可以写在这里",httpMethod = "POST")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径找不到")
})
@RequestMapping(value = "/findUser")
public User findUser(@RequestParam String userId){
//TODO
}
@ApiModel:用于JavaBean的类上面,表示此 JavaBean 整体的信息(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )
举例:
@ApiModel("用户信息类")
public class User {
@ApiModelProperty(value="用户id",name="id",dataType = "Integer",example="用户id",required = true)
private String id;
}
@ApiModelProperty:用在属性上,描述实体类的属性
value="用户名" 描述参数的意义
name="name" 参数的变量名
example="举例说明 "
hidden="true" 隐藏
dataType="重写属性类型"
required=true 参数是否必填
举例:
@ApiModel("用户信息类")
public class User {
@ApiModelProperty(value="用户id",name="id",dataType = "Integer",example="用户id",required = true)
private String id;
@ApiModelProperty(value="用户名",name="userName")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiParam:用在属性上,描述实体类的属性
name="参数名称"
value="参数的简要说明"
defaultValue="参数默认值"
required="true" 表示属性是否必填,默认为false
举例:
public User addUser(@ApiParam(value = "新增用户参数", required = true) @RequestBody User param) {
//TODO
}
二、 自定义注解的介绍(用来接收返回Map参数)
@ApiJsonObject:用在请求的方法上,包含一组参数说明
name="接收Map名称"
value={
@ApiJsonProperty:对单个参数的说明
key="key参数名称"
example="value值参数设置" 传参举例,默认是接参类型
type="参数类型" 默认String
description="参数描述"
}
举例:
@RequestMapping(value = "/userLogin",method = RequestMethod.POST)
@ApiOperation(value = "添加用户",notes = "添加公司用户")
@ApiJsonObject(name = "paramMap", value = {
@ApiJsonProperty(type = Integer.class,key = "id", example = "188xxxxxxx", description = "user phone"),
@ApiJsonProperty(type = String.class,key = "password", example = "123456", description = "user password"),
@ApiJsonProperty(type = String.class,key = "username", example = "", description = "user name"),
})
public SysResult userLogin(@RequestBody Map<String, Object> paramMap){
//TODO
}
@ApiReturnJson:用在请求的方法上,返回Map的说明(2.9.2版本默认正常显示)
name="返回Map名称"
value={
@ApiReturnJsonPro:对单个参数的说明
key="key参数名称"
description="参数描述"
type="参数类型" 默认String
}
举例:
@RequestMapping(value = "/userMap",method = RequestMethod.POST)
@ApiReturnJson(name = "returnMap", value = {
@ApiReturnJsonPro(key = "re1", description = "name",dataType = User.class),
@ApiReturnJsonPro(key = "re2", description = "password")
})
public Map test2(@RequestBody Map<String,Object> params){
//TODO
}
三、 Swagger的简单使用
Controller信息
调试步骤
四、 Swagger2 文档生成
运行服务打开Swagger复制Swagger文档地址,修改测试类生成文档
完成文档生成:可复制出来进行修改(用完注意删除生成的docs包)
代码(隐藏)
@SpringBootTest @RunWith(SpringRunner.class) public class SwaggerTest { //swagger文档地址 private final String Swagger2DocUrl = "http://127.0.0.1:8030/v2/api-docs"; /** * 生成AsciiDocs格式文档 * @throws Exception */ @Test public void generateAsciiDocs() throws Exception { // 输出Ascii格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL(Swagger2DocUrl)) .withConfig(config) .build() .toFolder(Paths.get("./docs/asciidoc/generated")); } /** * 生成Markdown格式文档 * @throws Exception */ @Test public void generateMarkdownDocs() throws Exception { // 输出Markdown格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.MARKDOWN) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL(Swagger2DocUrl)) .withConfig(config) .build() .toFolder(Paths.get("./docs/markdown/generated")); } /** * 生成Confluence格式文档 * @throws Exception */ @Test public void generateConfluenceDocs() throws Exception { // 输出Confluence使用的格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL(Swagger2DocUrl)) .withConfig(config) .build() .toFolder(Paths.get("./docs/confluence/generated")); } /** * 生成AsciiDocs格式文档,并汇总成一个文件 * @throws Exception */ @Test public void generateAsciiDocsToFile() throws Exception { // 输出Ascii到单文件 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL(Swagger2DocUrl)) .withConfig(config) .build() .toFile(Paths.get("./docs/asciidoc/generated/all")); } /** * 生成Markdown格式文档,并汇总成一个文件 * @throws Exception */ @Test public void generateMarkdownDocsToFile() throws Exception { // 输出Markdown到单文件 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.MARKDOWN) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL(Swagger2DocUrl)) .withConfig(config) .build() .toFile(Paths.get("./docs/markdown/generated/all")); } }
五、 Swagger2 API接口导入Postman使用
访问http://localhost:8030/swagger-ui.html 文档的首页,复制下面这个地址
打开postman–>import–>import Form Link
完成导入
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。