前言
在前面的博客中,我们将服务注册到了Eureka上,可以从Eureka的UI界面中,看到有哪些服务已经注册到了Eureka Server上,但是,如果我们想查看当前服务提供了哪些RESTful接口方法的话,就无从获取了,传统的方法是梳理一篇服务的接口文档来供开发人员之间来进行交流,这种情况下,很多时候,会造成文档和代码的不一致性,比如说代码改了,但是接口文档没有改等问题,而Swagger2则给我们提供了一套完美的解决方案,下面,我们来看看Swagger2是如何来解决问题的。
一、引入Swagger2依赖的jar包
<!-- swagger2 -->
<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>
二、初始化Swagger2的配置
@Configuration
@EnableSwagger2 // 启用Swagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {// 创建API基本信息
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.chhliu.jpa"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")// API 标题
.description("rdcloud-jpa提供的RESTful APIs")// API描述
.contact("chhliu@")// 联系人
.version("1.0")// 版本号
.build();
}
}
注:该配置类需要在Application同级目录下创建,在项目启动的时候,就初始化该配置类
三、完善API文档信息
public interface SonarControllerI {
@ApiOperation(value="获取项目组Sonar对应的Url信息", notes="根据id获取项目组Sonar对应的Url信息")// 使用该注解描述接口方法信息
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "SonarUrl表ID", required = true, dataType = "Long", paramType="path")
})// 使用该注解描述方法参数信息,此处需要注意的是paramType参数,需要配置成path,否则在UI中访问接口方法时,会报错
@GetMapping("/get/{id}")
SonarUrl get(@PathVariable Long id);
@ApiOperation(value="获取项目组Sonar对应的所有Url信息")
@GetMapping("/get/all")
List<SonarUrl> getAll();
}
注:paramType表示参数的类型,可选的值为”path”,”body”,”query”,”header”,”form”
四、完善返回类型信息
@Entity(name = "SONAR_URL")
public class SonarUrl implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="主键", hidden=false, notes="主键,隐藏", required=true, dataType="Long")// 使用该注解描述属性信息,当hidden=true时,该属性不会在api中显示
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ApiModelProperty(value="URL链接地址")
@Column(name="URL")
private String url;
@ApiModelProperty(value="项目组")
@Column(name="TEAM")
private String team;
@ApiModelProperty(value="部门")
@Column(name="DEPARTMENT")
private String department;
……省略getter,setter方法……
}
五、启动应用
1、在浏览器中输入:http://localhost:7622/swagger-ui.html
2、结果如下:
六、API文档访问与测试
Swagger除了提供API接口查看的功能外,还提供了调试测试功能
测试结果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
您可能感兴趣的文章:
- Spring Cloud中关于Feign的常见问题总结
- 深入理解Spring Cloud Zuul过滤器
- 解决Spring Cloud中Feign/Ribbon第一次请求失败的方法
- JSP spring boot / cloud 使用filter防止XSS
- spring cloud 之 客户端负载均衡Ribbon深入理解
- 深入解析Spring Cloud内置的Zuul过滤器
- spring cloud zuul修改请求url的方法
- 详解Spring Cloud Zuul中路由配置细节
- spring cloud 之 Feign 使用HTTP请求远程服务的实现方法
- 详解Spring Cloud Zuul重试机制探秘
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。



评论(0)