1. 程式人生 > 實用技巧 >好題選講(1)

好題選講(1)

api-node

SpringBoot介面文件

-----Swagger2生成API文件規則

2020.08.27

參考部落格:https://www.cnblogs.com/ynyhl/p/13322432.html

配置規則

  1. 導包
<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>
  1. 配置類
@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(&quot;yunqing&quot;, &quot;&quot;, &quot;yunqing****@gmail.com&quot;);
    return new ApiInfoBuilder()
            .title(&quot;SwaggerUI演示&quot;)
            .description(&quot;介面文件,描述詞省略200字&quot;)
            .contact(contact)
            .version(&quot;1.0&quot;)
            .build();
}

/**
 * 配置swagger2的靜態資源路徑
 * @param registry
 */
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 解決靜態資源無法訪問
    registry.addResourceHandler(&quot;/**&quot;)
            .addResourceLocations(&quot;classpath:/static/&quot;);
    // 解決swagger無法訪問
    registry.addResourceHandler(&quot;/swagger-ui.html&quot;)
            .addResourceLocations(&quot;classpath:/META-INF/resources/&quot;);
    // 解決swagger的js檔案無法訪問
    registry.addResourceHandler(&quot;/webjars/**&quot;)
            .addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;);
}


/**
 * 給API文件介面新增安全認證
 */
private List&lt;ApiKey&gt; securitySchemes() {
    List&lt;ApiKey&gt; apiKeys = new ArrayList&lt;&gt;();
    apiKeys.add(new ApiKey(&quot;Authorization&quot;, &quot;Authorization&quot;, &quot;header&quot;));
    return apiKeys;
}

private List&lt;SecurityContext&gt; securityContexts() {
    List&lt;SecurityContext&gt; securityContexts = new ArrayList&lt;&gt;();
    securityContexts.add(SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex(&quot;^(?!auth).*$&quot;)).build());
    return securityContexts;
}

private List&lt;SecurityReference&gt; defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope(&quot;global&quot;, &quot;accessEverything&quot;);
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    List&lt;SecurityReference&gt; securityReferences = new ArrayList&lt;&gt;();
    securityReferences.add(new SecurityReference(&quot;Authorization&quot;, authorizationScopes));
    return securityReferences;
}

}

  1. ShiroConfig或者SecurityConfig放置swagger2配置類資源
filterChainDefinitionMap.put("/swagger-ui.html**", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/swagger-resources/**", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon"); 

註解規則

  1. @Api : 請求類 與Controller放在一起 說明類的作用

eg.

@Api(tags = "賬戶相關模組")
@RestController
@RequestMapping("/api/account")
public class AccountController{
    // TODO 
}
  1. @ApiOperation 請求方法說明

eg.

@ApiOperation(value = "修改密碼", notes = "方法的備註說明,如果有可以寫在這裡")
@PostMapping("/changepass")
	public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo, @RequestBody @Valid PasswordModel passwordModel) {
    // TODO
 }
  1. @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
}
  1. @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
}
  1. @ApiModel:用於JavaBean上面,表示一個JavaBean
  2. @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 本地不能一直跑