springboot-swagger接口配置

在写接口的时候,程序员都需要进行方法验证,swagger是一个非常好用的接口展示工具,能够直观的测试接口,少用postman

 

直接上代码:

    首先maven配置jar包:

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

    swagger配置:




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;


@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        Docket docket = null;
        docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.jdddata.dic.base.service.match.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("奖微服务RESTful APIs")
                .description("XXXXX")
                .termsOfServiceUrl("www.jdd.com")
                .contact("微服务小组")
                .version("1.0")
                .build();
    }
}


basePackage中一定要写清楚扫描controller包地址!

在接口中加入参数配置:

@Api(value = "基本信息", description = "基本信息")
@RestController
@RequestMapping("/base/match/live")
public class MatchLiveController {

    @Resource
    private MatchAnalyzeLiveService matchLiveService;

    @ApiOperation(
            value = "接口描述",
            notes = "",
            response = MatchCardDto[].class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pcode", value = "类型:ios,android,h5", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "matchId", value = "13245886", required = true, dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/cards",method = {RequestMethod.POST, RequestMethod.GET})
    public List<MatchCardDto> getCardsInfo(@RequestParam(name = "pcode", required = false) String pCode,
                                           @RequestParam(name = "matchId", required = true) String matchId) {
        return matchLiveService.getLiveCardInfo(matchId);
    }

}

在做接口输出的过程中我发现,一味地遵守restful接口输出原则,会让接口变得晦涩难懂,所以可以在便于理解的情况下对接口进行稍加处理。

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