背景介紹:
Swagger是一個用於java代碼中寫註解,然後可以通過訪問指定的網頁,自動生成接口文檔,並且可以通過接口進行功能測試。
使用介紹:
(1)添加Maven依賴
<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>
(2)Java代碼中設置Swagger2Confg.java
package com.example.demo;
import com.fasterxml.classmate.TypeResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.WildcardType;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.alternateTypeRules(
newRule(typeResolver.resolve(Result.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class))
)
;
}
/**
* 創建該API的基本信息(這些基本信息會展現在文檔頁面中)
* 訪問地址:http://項目實際地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2構建RESTful APIs")
.description("更多請關注http://www.baidu.com")
.termsOfServiceUrl("http://www.baidu.com")
.contact("sunf")
.version("1.0")
.build();
}
}
(4)api接口調用示例
package com.example.demo;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@RestController
@Api(value = "DemoController | 一個用來測試swagger註解的控制器")
public class DemoController {
public String getUserByGet() {
return "1";
}
/**
* get方法demo
*
* @param userId
* @return
*/
@ApiOperation(value = "根據id獲取用戶信息(Get方法)")
@ApiImplicitParam(paramType = "query", name = "userId", value = "用戶id", required = true, dataType = "Integer")
@GetMapping("/getUser")
public String getUserByGet(Integer userId) {
return "success" + userId;
}
/**
* get pathVariable demo
*
* @param userId
* @return
*/
@ApiOperation(value = "根據id獲取用戶信息(PathVariable方法)", notes = "僅1和2返回正確信息", httpMethod = "GET")
@GetMapping("/getUser/{userId}")
public String getUserByPathVariable(@ApiParam(name = "userId", value = "用戶id", required = true) @PathVariable Integer userId) {
if (userId == 1 || userId == 2) {
return "success" + userId;
} else {
return "error";
}
}
/**
* post 傳入json數據 demo
*
* @param user
* @return
*/
@ApiOperation(value = "插入用戶數據", notes = "用json數據插入")
@PostMapping("/insertUser")
public Result<User> insetUser(@RequestBody @ApiParam(name = "用戶對象", value = "傳入json格式", required = true) User user) {
Result result = new Result();
result.setCode(200);
result.setData(user);
return result;
}
}
(5)成功加載的效果圖如下
(6)如果覺得上面的uri不好看的話,可以用如下的包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>0.0.2</version>
</dependency>
參考文檔: