好題選講(1)
阿新 • • 發佈:2020-09-14
SpringBoot介面文件
-----Swagger2生成API文件規則
2020.08.27
參考部落格:https://www.cnblogs.com/ynyhl/p/13322432.html
配置規則
- 導包
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency>
- 配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//為當前包下controller生成API文件
.apis(RequestHandlerSelectors.basePackage("com.troila"))
//為有@Api註解的Controller生成API文件
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//為有@ApiOperation註解的方法生成API文件
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//為任何介面生成API文件
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
//新增登入認證
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
Contact contact = new Contact("yunqing", "", "yunqing****@gmail.com");
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("介面文件,描述詞省略200字")
.contact(contact)
.version("1.0")
.build();
}
/**
* 配置swagger2的靜態資源路徑
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解決靜態資源無法訪問
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
// 解決swagger無法訪問
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// 解決swagger的js檔案無法訪問
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* 給API文件介面新增安全認證
*/
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>();
apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeys;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$")).build());
return securityContexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
}
- ShiroConfig或者SecurityConfig放置swagger2配置類資源
filterChainDefinitionMap.put("/swagger-ui.html**", "anon"); filterChainDefinitionMap.put("/v2/api-docs", "anon"); filterChainDefinitionMap.put("/swagger-resources/**", "anon"); filterChainDefinitionMap.put("/webjars/**", "anon");
註解規則
- @Api : 請求類 與Controller放在一起 說明類的作用
eg.
@Api(tags = "賬戶相關模組")
@RestController
@RequestMapping("/api/account")
public class AccountController{
// TODO
}
- @ApiOperation 請求方法說明
eg.
@ApiOperation(value = "修改密碼", notes = "方法的備註說明,如果有可以寫在這裡")
@PostMapping("/changepass")
public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo, @RequestBody @Valid PasswordModel passwordModel) {
// TODO
}
- @ApiImplicitParams、@ApiImplicitParam:方法引數的說明
eg.多引數
@ApiOperation(value="使用者登入",notes="隨邊說點啥")
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手機號",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public AjaxResult login(@RequestParam String mobile, @RequestParam String password,
@RequestParam Integer age){
//TODO
return AjaxResult.OK();
}
eg.單引數
@ApiOperation("根據部門Id刪除")
@ApiImplicitParam(name="depId",value="部門id",required=true,paramType="query")
@GetMapping("/delete")
public AjaxResult delete(String depId) {
//TODO
}
- @ApiResponses、@ApiResponse:方法返回值的說明
@ApiOperation(value = "修改密碼", notes = "方法的備註說明,如果有可以寫在這裡")
@ApiResponses({
@ApiResponse(code = 400, message = "請求引數沒填好"),
@ApiResponse(code = 404, message = "請求路徑找不到")
})
@PostMapping("/changepass")
public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo,
@RequestBody @Valid PasswordModel passwordModel) {
//TODO
}
- @ApiModel:用於JavaBean上面,表示一個JavaBean
- @ApiModelProperty:用在JavaBean的屬性上面,說明屬性的含義
eg. 一個POJO類
@ApiModel("修改密碼所需引數封裝類")
public class PasswordModel
{
@ApiModelProperty("賬戶Id")
private String accountId;
//TODO
}
關於Swagger2 @ApiModel的一個坑
使用swagger的 @ApiModel註解的時候有個坑 就是必須在controller 使用 @RequestBody 註解 否則無法顯示models
import io.swagger.v3.oas.annotations.parameters.RequestBody;
而且不報錯,此時swagger就和 spring 耦合了,而且問題難以排查,
1、@requestBody註解常用來處理content-type不是預設的application/x-www-form-urlcoded編碼的內容,比如說:application/json或者是application/xml等。一般情況下來說常用其來處理application/json型別。
2、通過@requestBody可以將請求體中的JSON字串繫結到相應的bean上,當然,也可以將其分別繫結到對應的字串上。
3 springBoot 中 使用@requestBody註解的話, 前端傳遞引數時需要JSON格式的引數,而且Content-Type為:application/json;charset=UTF-8 格式
@RequestBody的使用需要載入MappingJackson2HttpMessageConverter,但是SpringBoot的官方文件提到,這個是預設已經載入的了
沒好啊....
彩蛋
將Swagger文件匯入postman
postman-->import-->import from link
把公網ip匯入 ok 本地不能一直跑