好久没写博客了,近期闲来无事,所以利用这个时间记录下工作中常用到的工具之一swagger。
Swagger是一个流行的API开发框架,整合了RESTful风格与SpringMVC的特点。这个框架以“开放API声明”(OpenAPI Specification,OAS)为基础,对整个API的开发周期都提供了相应的解决方案,是一个非常庞大的项目(包括设计、编码和测试,几乎支持所有语言)。
那么maven项目怎样集成swagger的呢?
首先引入swagger依赖,
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
然后写swagger配置类,代码如下:
@EnableSwagger2
@Configuration
public class SwaggerUIConfig {
@Bean
public SwaggerProperties swaggerProperties() {
return new SwaggerProperties();
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerProperties().isEnable())
.groupName("...服务系统").apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage(SwaggerUIConfig.PACKAGE)).paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("...服务")
.description("...服务系统")
.version("v1.0").build();
}
private static final String PACKAGE= "com.cn.cdm.controller";
}
如果是多环境开发,就再引入一个配置类如下图所示
在开发/测试环境配置文件中写对应的key-value如:carrefour.swagger.enable=true
如图所示:
这样,多环境下的swagger相关配置就完成了。
相关的类、方法、入参注解这里就简单介绍下:
@Api()用于类; 表示标识这个类是swagger的资源
@ApiOperation()用于方法; 表示一个http请求的操作
@ApiModelProperty()多用于实体方法,字段 表示对model属性的说明或者数据操作更改
@ApiParam()用于方法,参数,字段说明(其实入参有多种写法,根据业务需求不同,可以用相应的注解,这里就不细说了大家自行百度下吧)
swagger页面访问路径:http://localhost:8080/swagger-ui.html
效果如下