swagger简介:
swagger是一款开源的api接口文档生成工具。
Swagger的项目主页:https://swagger.io/ 目前比较流行的做法是在代码中加入swagger相关的注释,然后,利用小工具生成swagger.json或者swagger.yaml文件。
springboot将swagger变得更加简单:
springboot拥有自己的自动配置特性,而swagger也发布了应用于springboot的自动依赖配置模块。
也就是说,只需要在pom文件中引入swagger模块配置信息,然后在application中进行swagger框架的简单配置,即可轻松通过浏览器访问由swagger为我们生成的网页版接口说明文档。
具体步骤:
1.首先我们需要在pom.xml中加入swagger模块配置信息,将swagger模块引入到项目中:
<!-- https://mvnrepository.com/artifact/com.spring4all/spring-boot-starter-swagger --> <dependency> <groupId>com.spring4all</groupId> <artifactId>spring-boot-starter-swagger</artifactId> <version>1.5.1.RELEASE</version> </dependency>
2.在springboot启动类中加入注解:
@EnableSwagger2Doc @SpringBootApplication public class Bootstrap { public static void main(String[] args) { SpringApplication.run(Bootstrap.class, args); } }
3.加入swagger配置信息:
在网上看到有两种配置方式,一种是另起一个application.yaml,然后通过yaml语言进行配置,另一种方式是在已有的application.properties中加入配置(这里记载第二种方式):
#swagger配置信息 swagger.title=yyh project online API specification swagger.description=the web page which you opened is generated by swagger automatically swagger.version=1.5.0.RELEASE swagger.license=Apache License, Version 2.0 swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger swagger.contact.name=mht swagger.contact.url=http://localhost:8084/swagger-ui.html [email protected] swagger.base-package=com.seco swagger.base-path=/** swagger.exclude-path=/error, /ops/**
#配置说明: swagger.title=标题 swagger.description=描述 swagger.version=版本 swagger.license=许可证 swagger.licenseUrl=许可证URL swagger.termsOfServiceUrl=服务条款URL swagger.contact.name=维护人 swagger.contact.url=维护人URL swagger.contact.email=维护人email swagger.base-package=swagger扫描的基础包,默认:全扫描 swagger.base-path=需要处理的基础URL规则,默认:/** swagger.exclude-path=需要排除的URL规则,默认:空
4.API文档效果查看:
启动项目,打开浏览器在地址栏输入如下地址即可查看生成的API文档:
http://localhost:8080/swagger-ui.html
参考文章:
《简化Swagger使用的自制Starter:spring-boot-starter-swagger,欢迎使用和吐槽》
《使用spring-boot-starter-swagger实现API文档化》