初次学习swagger,文章内容参考自:didispace.com/spring-boot-learning-21-2-2/
1、swagger介绍
swagger可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。
2、swagger整合springboot
2.1 搭建一个简单的restful的springboot工程,略。
2.2 引入swagger坐标。`
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
2.3 在主启动类上添加 @EnableSwagger2Doc
@SpringBootApplication
@EnableSwagger2Doc
public class Swager2Application {
public static void main(String[] args) {
SpringApplication.run(Swager2Application.class, args);
}
}
2.4 在application.properties文件中添加swagger相关信息
swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.4.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=bulldog
swagger.contact.url=http://www.baidu.com
swagger.contact.email=12345678@qq.com
swagger.base-package=com.example.swagger2
swagger.base-path=/**
各参数配置含义如下:
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规则,默认:/**
2.5 启动项目
查看http://localhost:8080/swagger-ui.html,在最下面可以看到我们自己的接口信息,点开后可以测试try it out。
3、增加说明性内容
我们通过@Api,@ApiOperation注解来给API增加说明、通过@ApiImplicitParam、@ApiModel、@ApiModelProperty注解来给参数增加说明。
再来看下swagger接口文档界面:
可以通过@ApiModel(description=“x”)和@ApiModelProperty(“x”)来给实体类添加说明。
@Data
@ApiModel(description="用户实体")
public class User {
@ApiModelProperty("用户编号")
private Long id;
@ApiModelProperty("用户姓名")
private String name;
@ApiModelProperty("用户年龄")
private Integer age;
}
文章内容参自大牛程序员DD的博客:didispace.com/spring-boot-learning-21-2-2/