RESTful API 介绍
- 由于Spring Boot能够快速开发、便捷部署等特性,很大一部分Spring Boot的用户会用来构建RESTful API。而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。
spring boot 整合 Swagger2
- 效果
添加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配置类
- 在Application.java同级创建Swagger2的配置类Swagger2。
@Configuration //spring boot配置注解
@EnableSwagger2 //启用swagger2功能注解
public class Swagger2Config {
@Bean
public Docket createRestfulApi() {//api文档实例
return new Docket(DocumentationType.SWAGGER_2)//文档类型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())//api信息
.select()//构建api选择器
.apis(RequestHandlerSelectors.basePackage("com.yyh.controller"))//api选择器选择api的包
.paths(PathSelectors.any())//api选择器选择包路径下任何api显示在文档中
.build();//创建文档
}
private ApiInfo apiInfo() {//接口的相关信息
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful接口")
.description("接口描述")
.termsOfServiceUrl("termsOfServiceUrl")
.contact("new Contact")
.version("1.0")
.license("http://springfox.github.io/springfox/docs/current/")
.licenseUrl("http://springfox.github.io/springfox/docs/current/")
.build();
}
}
复制代码
如上代码所示,通过@Configuration注解,让Spring来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。
再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
添加文档内容(详细)
在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。 @RestController//接口注解 @Api(value="用户接口",tags={"dogAPi"})//接口简要标注,对中文的支持不太好 @RequestMapping(value = "/swagger")//接口基本路径
public class AnimalController {
//接口需要的参数,可以有多个,这里只写了一个,它的paramType还有path、query、body、form几种,
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "Token", value = "token", dataType = "String", required = true,defaultValue = "123")})
//接口功能描述
@ApiOperation(value = "获取一只狗")
//接口响应信息,这里定义了一个401,当出现401,接口返回的是自定的错误AnimalError的实例。当然可以定义多个。
@ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证.", response = AnimalError.class) })
@RequestMapping(value="/onedog", method = RequestMethod.GET)
public Dog oneDog(){
return new Dog();
}
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "Token", value = "token", dataType = "String", required = true,defaultValue = "123")})
@ApiOperation(value = "创建一只狗")
@ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证.", response = AnimalError.class) })
@RequestMapping(value="/dog/{name}", method = RequestMethod.GET)
public Dog createDog(
@ApiParam(defaultValue = "二哈")//@ApiParam和@RequestParam注解作用效果相同
@PathVariable("name") String name){
Dog dog = new Dog();
dog.setName(name);
return dog;
}
复制代码