swagger swagger-codegen 使用
Swagger使用
1. Swagger UI
按以下步骤配置,项目启动后访问:
http://localhost:8080/swagger-ui.html
1.1 添加依赖
<dependency><groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
1.2 配置类
@Configuration
@EnableSwagger2
public class Swagger2 { public static final String SWAGGER_SCAN_BASE_PACKAGE = "abc.boot.examples.web"; public static final String VERSION = "1.0.0"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))//api接口包扫描路径 .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger2 接口文档示例")//设置文档的标题 .description("更多内容请关注:http://www.abc.com")//设置文档的描述->1.Overview .version(VERSION)//设置文档的版本信息-> 1.1 Version information .contact(new Contact("ABC Boot", "http://www.abc.comt", ""))//设置文档的联系方式->1.2 Contact information .termsOfServiceUrl("www.abc.com")//设置文档的License信息->1.3 License information .build(); } }
1.3 注解使用
@ApiOperation
@ApiOperation(value="获取用户列表", notes="获取所有用户列表",produces = "application/json")
@RequestMapping(value="/users", method= RequestMethod.GET) public List<User> getUserList() { List<User> r = new ArrayList<User>(users.values()); return r; }
@ApiResponses
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息",produces = "application/json")
// ApiResponses 增加返回结果的描述 @ApiResponses(value = {@ApiResponse(code = 405,message = "Invalid input",response = Integer.class)}) (1) @ApiImplicitParam(name = "id",value = "用户ID",dataType = "int",paramType = "path") (2) @RequestMapping(value="/users/{id}", method= RequestMethod.GET) public User getUser(@PathVariable Integer id) { return users.get(id); }
(1) 在默认Response的基础上增加新的Response说明
(2) 使用ApiImplicitParam描述接口参数
@ApiImplicitParams
@ApiOperation(value="更新用户名称", notes="更新指定用户的名称")
@RequestMapping(value="/users/{id}", method= RequestMethod.POST) @ApiImplicitParams({ (1) @ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"), (2) @ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string") }) public void updateUserName(@PathVariable Integer id,@RequestParam String userName){ User u = users.get(id); u.setName(userName); }
(1) 使用ApiImplicitParams描述多个参数
(2) 使用ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式。
paramType 有五个可选值 : path, query, body, header, form
@ApiParam
@ApiOperation(value="创建用户-传递简单对象", notes="传递简单对象",produces = "application/json")
@RequestMapping(value="/users-1", method= RequestMethod.POST) //可以不加ApiParam注解,需要给参数添加描述时可以使用这个注解,或者使用ApiImplicitParams注解 (1) public Map postUser(@RequestParam String userName,@ApiParam("地址") @RequestParam(required = false) String address) { User user = new User(); user.setId(Math.round(10)); user.setName(userName); user.setAddress(address); users.put(user.getId(), user); return ImmutableMap.of("user",user); }
(1) 使用ApiParam描述接口参数
ApiImplicitParam 与 ApiParam 的区别
ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.
- 对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
- 在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
- ApiParam只需要较少的属性,与swagger ui配合更好。
传递复杂对象 By ModelAttribute
@ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO, url参数拼接",produces = "application/json")
@RequestMapping(value="/users-2", method= RequestMethod.POST) //传递对象推荐使用ModelAttribute注解 public Map postUser2(@ModelAttribute User user) { (1) users.put(user.getId(),user); return ImmutableMap.of("user",user); }
(1) ModelAttribute 是Spring mvc的注解,这里Swagger可以解析这个注解,获得User的属性描述
@ApiModel
@ApiModel(value = "User", description = "用户对象")
public class User { @ApiModelProperty(value = "ID") private Integer id; @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "地址") private String address; @ApiModelProperty(value = "年龄",access = "hidden") private int age; @ApiModelProperty(value = "性别") private int sex; ....... }
传递复杂对象 By RequestBody
@ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO,json格式传递数据",produces = "application/json")
@RequestMapping(value="/users-3", method= RequestMethod.POST) //json格式传递对象使用RequestBody注解 public User postUser3(@RequestBody User user) { users.put(user.getId(),user); return user; }
PathVariable
@ApiOperation(value="删除用户- PathVariable", notes="根据url的id来指定删除对象")
@RequestMapping(value="/users/{id}", method = RequestMethod.DELETE) public void deleteUser(@PathVariable Integer id) { (1) users.remove(id); }
(1) PathVariable是Spring 的注解,对于这种简单的参数,就可以不用写ApiParam来描述接口参数。
数组的描述
@ApiOperation(value="删除用户-传递数组", notes="删除对象,传递数组")
@RequestMapping(value="/users/deleteByIds", method = RequestMethod.DELETE) public void deleteUser(@ApiParam("用户ID数组") @RequestParam Integer[] ids) { (1) for (int id:ids){ users.remove(id); } }
(1) 这里用ApiParam为数组参数添加描述
1.4 可选配置
在application.properties中加入以下配置,用于设置测试请求的host,默认在swagger ui上做请求测试时都是以/users/1为路径发送请求。
如果需要改变请求的根路径,就需要配置这个参数:
springfox.documentation.swagger.v2.host = yourapp.abc.com
配置获取api docs json数据的请求路径 ,默认为/v2/api-docs:
springfox.documentation.swagger.v2.path = /api
2. springfox-staticdocs 生成静态文档
2.1 Maven 配置
<dependency><groupId>io.springfox</groupId> <artifactId>springfox-staticdocs</artifactId> <version>2.2.2</version> <scope>test</scope> </dependency>
2.2 生成json文件
编写Junit测试,这样在测试环节就可以将api-docs的json数据写入文档,便于下一步生成asciidoc文件。
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoBootApplication.class)
public class Swagger2MarkupTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); } @Test public void createSpringfoxSwaggerJson() throws Exception { String outputDir = "src/docs/json"; //将api-docs的json数据写入文件 MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String swaggerJson = response.getContentAsString(); Files.createDirectories(Paths.get(outputDir)); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) { writer.write(swaggerJson); } } }
2.3 配置Maven Plugin
配置以下两个插件:
swagger2markup-maven-plugin,该插件将json文件转为asciidoc
asciidoctor-maven-plugin, 该插件将asciidoc转为html/pdf
执行Maven命令 : mvn swagger2markup:convertSwagger2markup process-resources
生成的html文档存储在src\main\resources\META-INF\resources\docs目录下。
启动DemoBootApplication,直接访问http://localhost:8080/docs/index.html。
<pluginRepositories><pluginRepository> <id>jcenter-snapshots</id> <name>jcenter</name> <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url> </pluginRepository> <pluginRepository> <snapshots> <enabled>false</enabled> </snapshots> <id>jcenter-releases</id> <name>jcenter</name> <url>http://jcenter.bintray.com</url> </pluginRepository> </pluginRepositories> <build> <plugins> <!-- First, use the swagger2markup plugin to generate asciidoc --> <plugin> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup-maven-plugin</artifactId> <version>${swagger2markup.plugin.version}</version> <dependencies> <dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup-import-files-ext</artifactId> <version>${swagger2markup.extension.version}</version> </dependency> <dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup</artifactId> <version>${swagger2markup.version}</version> </dependency> </dependencies> <configuration> <!--The URL or file path to the Swagger specification--> <swaggerInput>${swagger.input}</swaggerInput> <outputDir>${generated.asciidoc.directory}</outputDir> <config> <!--设置输出文件的语言:ASCIIDOC, MARKDOWN, CONFLUENCE_MARKUP--> <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage> <!--设置目录的展现方式--> <swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy> <!--扩展Overview的内容,可以增加一些自定义的内容--> <!--<swagger2markup.extensions.dynamicOverview.contentPath>${project.basedir}/src/docs/asciidoc/extensions/overview</swagger2markup.extensions.dynamicOverview.contentPath> <swagger2markup.extensions.dynamicDefinitions.contentPath>${project.basedir}/src/docs/asciidoc/extensions/definitions</swagger2markup.extensions.dynamicDefinitions.contentPath> <swagger2markup.extensions.dynamicPaths.contentPath>${project.basedir}/src/docs/asciidoc/extensions/paths</swagger2markup.extensions.dynamicPaths.contentPath> <swagger2markup.extensions.dynamicSecurity.contentPath>${project.basedir}src/docs/asciidoc/extensions/security</swagger2markup.extensions.dynamicSecurity.contentPath>--> </config> </configuration> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>convertSwagger2markup</goal> </goals> </execution> </executions> </plugin> <!-- Run the generated asciidoc through Asciidoctor to generate other documentation types, such as PDFs or HTML5 --> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>1.5.3</version> <!-- Include Asciidoctor PDF for pdf generation --> <dependencies> <dependency> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctorj-pdf</artifactId> <version>1.5.0-alpha.11</version> </dependency> <!-- Comment this section to use the default jruby artifact provided by the plugin --> <dependency> <groupId>org.jruby</groupId> <artifactId>jruby-complete</artifactId> <version>${jruby.version}</version> </dependency> <!-- Comment this section to use the default AsciidoctorJ artifact provided by the plugin --> <dependency> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctorj</artifactId> <version>${asciidoctorj.version}</version> </dependency> </dependencies> <!-- Configure generic document generation settings --> <configuration> <!--默认指向 ${basedir}
swagger swagger-codegen 使用相关推荐
- swagger 返回json字符串_[Swagger] Swagger Codegen 高效开发客户端对接服务端代码
[Swagger] Swagger Codegen 高效开发客户端对接服务端代码 @TOC 手机用户请横屏获取最佳阅读体验,REFERENCES中是本文参考的链接,如需要链接和更多资源,可以关注其他博 ...
- java camel swagger,Swagger将下划线转换为camelcase
因此,我在使用Swagger(Core 1.5.7)使用XML对象定义时遇到了麻烦.这里是我的XML代码:Swagger将下划线转换为camelcase 这是我的阳明代码: result: type: ...
- (十三)Alian 的 Spring Cloud 生成接口调用(swagger codegen)
目录 一.简介 二.Swagger Codegen 2.1.swagger-codegen-cli 2.2.获取依赖关系 2.3.发布到私服 三.项目整合 3.1.属性配置 3.2.控制层 3.3.生 ...
- Swagger (YAML OpenAPI) 从放弃到入门
Swagger 是一个统一前后端用于生成文档和代码的工具,它使用 yaml / json 作为描述语言 通过 OpenAPI Specification 来描述 API,最后使用 Codegen 根据 ...
- 配置 Swagger 文档的自动生成
Swagger Swagger 是一个开源工具.它围绕帮助开发人员设计.构建.记录和使用 RESTful API 的 OpenAPI 规范构建.它是 RESTful Web 服务最流行的 API 文档 ...
- Swagger工具详解
前言 小编前几天在学习了Swagger,一直都处于迷迷糊糊的,不太明白他的优势,单纯的认为只是提供给我们一个界面用于前后台的交互,其实还有很多其他的功能 What Swagger swagger表示用 ...
- Spring Boot 之 Swagger
文章目录 Swagger Swagger介绍 版本 使用 依赖 常用注解说明 配置类 皮肤定制 Swagger Swagger介绍 Swagger 是一套基于 OpenAPI 规范构建的开源工具 Op ...
- swagger ui 怎么输入对象_Swagger UI 传入对象类型参数
Swagger要传送对象作为参数,只需添加@ModelAttribute或@RequestBody @RestController @RequestMapping("/api/json/re ...
- vb6编写用户权限_仅需三行代码,即可让Apache Shiro接管Swagger权限认证
有很多文章提到,在生产环境中需要关闭Swagger功能,防止系统资源泄露.今天,我结合自己开发过程中的经验,分享一个只需几行代码便可实现让Apache Shiro接管Swagger认证和授权的方法.如 ...
- php怎么根据接口文档实现功能,CodeIgniter+swagger实现 PHP API接口文档自动生成功能...
一.安装swagger 1.首先需要有composer,没有的自行百度安装 2.下载swagger,打开网站https://packagist.org/packages/zircote/swagger ...
最新文章
- PHP封装返回Ajax字符串和JSON数组
- gpio_direction_output 与 gpio_set_value
- Matlab代码的耗时分析、优化、加速
- Pandas入门3(dtype+fillna+replace+rename+concat+join)
- OSPF(Open Shortest Path First)开放式最短路径优先协议05
- mysql 开发进阶篇系列 13 锁问题(关于表锁,死锁示例,锁等待设置)
- MYSQL数据库脱库写马写一句话
- USB redirection
- 生产企业ERP流程是什么
- [莓控]BlackBerry7290用户指南(简体中文)
- RLC电阻电感电容取值标准
- 南京中山陵环卫工和游客当众互殴(图)
- Kubernetes网络flannel之host-gw模式分析
- 手机语言 Symbian 术语表
- 小测试整理(含T1 T2)
- android项目修改名字(app名称),运行在移动设备和模拟器上的项目名字
- js:nodejs中的session(登陆验证)
- html类选择器使用在什么场景,你需掌握的CSS知识都在这了(长文建议收藏,文末有福利)...
- 基于FFmpeg的视频播放器之十一:倍速播放
- Weblogic11g 在linux安装详解
热门文章
- 2021-02-26js学习-arguement,函数,作用域链,js代码执行流程,对象创建,new执过程.
- Python类实例化时出现 take no arguements 的错误
- Apexテストコード作成の落とし穴
- 华东师大计算机系博士几年,2018华东师范大学就业结果公布!就业率超97%,博士生月薪1.1万!...
- 无线蓝牙模块的体积会影响传输距离吗?
- php中实现图片自动轮播,基于vue.js实现图片轮播效果
- 19.Java复习(二)
- hive小文件处理方法
- 元宇宙(metaverse)的认知记录
- 解决MySQL报错:LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.