理想情况下,为所开发的服务编写接口文档,能提高与周边系统对接联调的效率.但前提条件是,服务和API文档必须是同步更新的,如果不能保证同步,那接口文档就会流于形式,不仅不能起到应有的作用,甚至某些情况下,甚至会误导对接的系统,导致更低效率的沟通.
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>${springfox-swagger2.version}version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>${springfox-swagger2.version}version>
dependency>
@Configuration
@EnableSwagger2
public class Swagger2Config {
}
@Bean
public WebMvcConfigurerAdapter addResourceHandlers() {
return new WebMvcConfigurerAdapter() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
};
}
注意点 : 版本号和项目名称可在配置文件中定义(从pom中取)
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.egridcloud")).paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
apiInfoBuilder.title(this.projectName + " online api document");
apiInfoBuilder.version(version);
return apiInfoBuilder.build();
}
@RestController
@RequestMapping("demo")
@Api(value = "demo",
consumes = "application/json",
produces = "application/json",
protocols = "http")
public class DemoController {
}
@ApiOperation(value = "add", notes = "add")
@RequestMapping(value = "add", method = RequestMethod.GET)
public RestResponse add(Integer a, Integer b) {
return new RestResponse<>(demoService.add(a, b));
}
@ApiOperation(value = "add", notes = "add")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "a", value = "a", required = true,
dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "b", value = "a", required = true,
dataType = "int") })
@RequestMapping(value = "add", method = RequestMethod.GET)
public RestResponse add(Integer a, Integer b) {
return new RestResponse<>(demoService.add(a, b));
}
@ApiModel(description = "响应消息体")
public class RestResponse<T> implements Serializable {
/**
*
* 描述 : id
*
*/
private static final long serialVersionUID = 1L;
/**
* 描述 : 响应ID
*/
@ApiModelProperty(value = "响应ID", required = true, dataType = "string")
private String id = UUID.randomUUID().toString();
.............
}
以上配置结束之后,启动项目,访问http://xxxxx/swagger-ui.html
即可能够访问接口文档,并且直接可以做接口调用测试.
然后对于Swagger2这个组件,目前看下来就是对业务代码有一定的入侵,总之使用前请根据自身项目情况做好评估,不要盲目跟风.
想获得最快更新,请关注公众号