项目中前后端对接接口经常需要有接口文档,如果自己写的话费时费力,还容易出错,今天介绍swagger,可以让我们使用注解对类,方法,入参,实体类进行说明,省去我们写接口的时间,示例简单使用如下:
1:引入依赖注解
<!--swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
2:生成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;
@Configuration
public class Swagger2Config {
@Bean
public Docket creatResetApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.qingnian.spring.controller"))//需要扫描的controller包路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger构建接口文档")
.description("测试用例")
.termsOfServiceUrl("http://www.baidu.com")
.version("1.0")
.build();
}
}
3:对应的方法,接口入参。映射实体类进行标注说明
import com.qingnian.spring.domain.Student;
import com.qingnian.spring.service.StudentService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("student")
@Api(value = "学生表",description = "学生的基本操作",tags = "学生信息")
public class SwaggerStudentController {
@Autowired
private StudentService studentService;
@GetMapping("/get/one")
@ApiOperation(value="查询单条记录",notes = "查询")
//@ApiImplicitParam(name="id",defaultValue ="", value = "主键id",required = true,dataType ="Integer" )
public Student getOneInfo(@RequestParam(value = "id",defaultValue = "")@ApiParam(value="主键id") Integer id){
return studentService.selectOne(id);
}
}
@Data
@ApiModel
public class Student implements Serializable {
@ApiModelProperty(name="主键",notes="主键",dataType = "int")
private int id;
@ApiModelProperty(name="姓名",notes="姓名",dataType = "String")
private String name;
private int age;
private String email;
private String address;
private String sex;
private String crtTime;
private String updTime;
}
然后我们可以在页面上获取对应接口的详细信息
http://ip地址:服务端口号/swagger-ui.html#/