Swagger使用及常見問題

Spring Boot中使用

在pom.xml中注入依賴

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
 

然後編輯配置文件SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket userApi() {

     Predicate<RequestHandler> swaggerSelector = (Predicate<RequestHandler>)RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class);

        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(newArrayList(new ApiKey[]{this.apiKey()}))
//               .securitySchemes(newArrayList(new BasicAuth("test"))) //賬號密碼登錄
//               .enable(false)   //禁止使用
                .apiInfo(apiInfo())
                .select()
//               .apis(RequestHandlerSelectors.basePackage("com.boot"))
                .apis(swaggerSelector)
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("**接口")
                .description("構建restful api")     
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .contact("name")
                .version("1.0.0")
                .build();
    }


    ApiKey apiKey() {
        return new ApiKey("sessionId", "sessionId", "header");
    }
}

註解使用

@Api(value = "TestController", description = "**系統", produces = MediaType.APPLICATION_JSON_VALUE)
@Controller
public class TestController {
    @ApiOperation(value = "查找所有用戶",notes = "注意")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userEmail",value="用戶郵箱",dataType="string", paramType = "query",example="test"),
            @ApiImplicitParam(name="display",value="展示",dataType="string", paramType = "query")})
    @GetMapping("/test")
    @ResponseBody
    public Result findAllUser(String userEmail, String display)throws Exception{
    
    }

使用過程中常見問題
1、api接口沒有問題,可以用Postman測試成功,但是swagger測試報錯,就是註解中的參數paramType沒等於query,增加上即可
@ApiImplicitParam(name="name",value="用戶名",dataType="String", paramType = "query")

2、填寫完註解後,在網頁上看到每個接口都有GET、POST、DELETE等多種請求方式,要在註解中添加httpMethod = "POST"
 @ApiOperation(value = "用戶與系統對應關係",httpMethod = "POST")

 

有的版本寫法不一樣,有的可能是 method = RequestMethod.GET

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章