集成swagger到JavaWeb项目中
在此之前,我们使用PostMan进行模拟测试。
一般来说,开发前我们会先定义好接口,这样子前端开发人员,后端开发人员可以同时开工了。
那么我们web开发,怎么样才更方便查看接口和测试接口呢?
我们可以集成swagger
添加依赖
<!-- RESTful APIs swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
然后导入一下
编写配置文件
Swagger2Configuration
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
//版本
public static final String VERSION = "1.0.0";
/**
* 门户api,接口前缀:portal
*
* @return
*/
@Bean
public Docket portalApi() {
return new Docket(DocumentationType.SWAGGER_12)
.apiInfo(portalApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("net.sunofbeach.blog.controller.portal"))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build()
.groupName("前端门户");
}
private ApiInfo portalApiInfo() {
return new ApiInfoBuilder()
.title("阳光沙滩博客系统门户接口文档") //设置文档的标题
.description("门户接口文档") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
/**
* 管理中心api,接口前缀:admin
*
* @return
*/
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_12)
.apiInfo(adminApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("net.sunofbeach.blog.controller.admin"))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build()
.groupName("管理中心");
}
private ApiInfo adminApiInfo() {
return new ApiInfoBuilder()
.title("阳光沙滩管理中心接口文档") //设置文档的标题
.description("管理中心接口") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
@Bean
public Docket UserApi() {
return new Docket(DocumentationType.SWAGGER_12)
.apiInfo(userApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("net.sunofbeach.blog.controller.user"))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build()
.groupName("用户中心");
}
private ApiInfo userApiInfo() {
return new ApiInfoBuilder()
.title("阳光沙滩博客系统用户接口") //设置文档的标题
.description("用户接口的接口") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
}
在controller创建各个包
相关的注解
详情请看视频演示吧。