SpringBoot集成API文档工具Swagger

当前比较流行前后端分离式开发,提供详细的后端API接口文档,对于前端开发和后端开发都是比较重要的。开发者可以查阅和搜索API文档,并可以直接切换接口调试,提高了开发效率。Swagger是用于Restful API开发的工具,可以动态生成Api接口文档,降低沟通成本。

  • OpenAPI Specification:API规范,规定了如何描述一个系统的API
  • Swagger Codegen:用于通过API规范生成服务端和客户端代码
  • Swagger Editor:用来编写API规范
  • Swagger UI:用于展示API规范

Springfox 把Swagger集成进Spring,底层还是Swagger,使用方便。 http://springfox.github.io/springfox/  

pom.xml 


<!--spring-fox依赖-->

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.9.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.9.2</version>

</dependency>

Springboot启动类添加@EnableSwagger2注解


@Configuration

@EnableSwagger2

public class SwaggerConfig {



    @Bean

    public Docket defaultApi() {

        return new Docket(DocumentationType.SWAGGER_2)

            .apiInfo(apiInfo())

            .select()

            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

            .paths(PathSelectors.any())

            .build();

    }



}

API注解


@Api(tags=数据字典)

@RestController

@RequestMapping(/sys/dict)

public class SysDictController extends BaseController {

	

	@Autowired

	SysDictService sysDictService;

	

	@ApiOperation(创建字典)

	@RequestMapping(value=/create, method=RequestMethod.POST)

	public Result create(@RequestBody SysDict sysDict) {

		return success(sysDictService.save(sysDict));

	}



}

启动项目浏览API文档

http://localhost:8080/swagger-ui.html 

API常用注解

@Api 用在controller类,描述API接口
@ApiOperation 描述接口方法
@ApiModel 描述对象
@ApiModelProperty 描述对象属性
@ApiImplicitParams 描述接口参数
@ApiResponses 描述接口响应

 

Linux文件镜像同步方案 工具rsync Springboot 定义接口方法同时支持GET和POST请求
微信公众号