在做项目的时候对于api的规范特别重要,以前用了swagger,感觉挺好用,但是就是有点麻烦,现在springboot中可以使用注解的方式来逆向生成swagger文档,以下是使用步骤:1.在pom文件中引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2.在项目的配置文件中添加一个config文件夹,里面添加一个配置类,用来描述哪些包下面会被扫描变成swagger文档@Configuration@EnableSwagger2public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(“com.manage”))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“网页api文档”)
.description(“网页api文档”)
// .termsOfServiceUrl(“/”)
.version(“1.0″)
.build();
}
}在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下:@Api:修饰整个类,描述Controller的作用 @ApiOperation:描述一个类的一个方法,或者说一个接口@ApiParam:单个参数描述 @ApiModel:用对象来接收参数 @ApiModelProperty:用对象接收参数时,描述对象的一个字段 @ApiResponse:HTTP响应其中1个描述 @ApiResponses:HTTP响应整体描述 @ApiIgnore:使用该注解忽略这个API @ApiError :发生错误返回的信息@ApiImplicitParam:一个请求参数@ApiImplicitParams:多个请求参数@ApiImplicitParam属性:例子://首先在接口上面描述接口的作用,详情和参数@Api(value=”页面管理接口”,description = “页面管理接口,提供页面的增、删、改、查”)public interface PageControllerApi {@ApiOperation(“分页查询页面列表”)@ApiImplicitParams({@ApiImplicitParam(name=”page”,value = “页码”,required=true,paramType=”path”,dataType=”int”),@ApiImplicitParam(name=”size”,value = “每页记录数”,required=true,paramType=”path”,dataType=”int”)})public QueryResponseResult findList(int page, int size) ;}
//使用@ApiModelProperty描述模型类的各个字段@Datapublic class QueryPageRequest {
//接受页面的条件参数
//站点id
@ApiModelProperty(“页面id”)
String pageId;
}
发表回复