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

 

 

 

 

 

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