在寫接口的時候,程序員都需要進行方法驗證,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接口輸出原則,會讓接口變得晦澀難懂,所以可以在便於理解的情況下對接口進行稍加處理。