这篇文章主要介绍了spring cloud整合Swagger2如何构建RESTful服务的APIs,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
一、引入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整合Swagger2如何构建RESTful服务的APIs”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。