前后端分离的开发模式对大家来说已经不再陌生,开发联调环节后端api接口文档对项目进度来说是一个痛点,尤其是在规模较大的研发团队或微服务项目,目前比较省事的解决方案是集成Swagger2框架,网上也有不少关于Swagger2的帖子,本文主要分享基于Swagger2最新版本3.0.0的搭建过程(红色字体部分为区别于老版本的地方):
1、引入依赖包:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2、Swagger2配置
@Configuration
@EnableOpenApi
public class Swagger2Config implements WebMvcConfigurer {
/**
* 是否开启swagger配置,生产环境需关闭
*/
@Value("${swagger.enabled}")
private boolean enable;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30).pathMapping("/")
.enable(enable)
.apiInfo(this.apiInfo())
.select() // 指定需要发布到Swagger的接口目录,不支持通配符
.apis(RequestHandlerSelectors.basePackage("com.bdtx.commons.web"))
.paths(PathSelectors.any())
.build()
// 支持的通讯协议集合
.protocols(this.newHashSet("https", "http"));
}
/**
* 项目信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Swagger Api Doc")
.description("SpringBoot后台接口")
.contact(new Contact("user", null, "xyz@qq.com"))
.version("Application Version: 1.0.0")
.build();
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts) {
if (ts.length > 0) {
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
}
新版本的注解用的是@EnableOpenApi,Docket的DocumentationType是OAS_30
此时启动项目就已经可以正常访问接口文档页面了:http://localhost:8080/swagger-ui/index.html
3、创建接口
@RestController
@Api(tags = "测试接口") // description属性已过期废弃
public class HelloController {
@ApiOperation(value = "测试接口1", notes = "测试Get接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value="姓名", required = true, dataTypeClass = String.class),
@ApiImplicitParam(name = "age", value="年龄", required = true, dataTypeClass = Integer.class),
})
@GetMapping("getTest")
public String getTest(String name, Integer age) {
return name + age;
}
@ApiOperation(value = "测试接口2", notes = "测试Post接口")
@ApiImplicitParam(name = "hello", value="对象参数", required = true, dataType = "Hello", dataTypeClass = Hello.class)
@PostMapping("postTest")
public String postTest(@RequestBody Hello hello) {
return hello.getName();
}
}
Swagger3.0.0版本多了一个dataTypeClass属性,默认值是Void.class,接口参数建议指定该属性,否则项目启动时会有不少数据类型无法解释的警告:
Unable to interpret the implicit parameter configuration with dataType: Hello, dataTypeClass: class java.lang.Void
上面的第二个接口参数是一个对象,在实体类中的描述与老版本无区别:
@ApiModel(value = "Hello", description = "测试Dto")
public class Hello {
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "年龄")
private int age;
//setter/getter
}
至此就完成了SpringBoot对Swagger2最新版本3.0.0的整合: