SpringBoot项目API文档工具-Springfox Swagger

本文介绍如何使用Springfox为SpringBoot项目快速生成高质量API文档。通过配置和使用特定注解,Springfox能够自动生成详尽的API文档,极大提高开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介

  我们编写的Rest API,是给另外的团队使用的,所以怎样告知使用者他们需要的信息,也是API开发者需要关注,好的API文档不仅能让使用者尽快上手,而且也能让开发者日后维护项目时提高效率。这么说来,API文档越详细越好,比如笔者刚开始工作的时候,API文档都是用word一点点描写清楚的,但是这样光写文档就花了不少时间,所以如果能兼具质量与效率,那将是多么美好,可是很多时候,质量与效率是对立的,但是在API文档上,Springfox项目就做到了兼具效率与质量。

二、创建项目

  为了演示方便,我们就简单创建一个spring boot项目,gradle配置如下,其中主要使用的就是springfox的依赖。

buildscript {
	ext {
		springBootVersion = '1.5.6.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
}


dependencies {
	compile(
			'org.springframework.boot:spring-boot-starter-web',
			'io.springfox:springfox-swagger2:2.7.0',
			'io.springfox:springfox-swagger-ui:2.7.0'
	)
	testCompile('org.springframework.boot:spring-boot-starter-test')
}
  项目启动入口就是简单的springboot启动了,如下。

package com.nan.swaggerdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SwaggerdemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SwaggerdemoApplication.class, args);
	}
}
  接下来就是比较重要的springfox配置,主要配置api的作者版本以及扫描方法等信息,如下。其中有2个方面比较重要,一是要加上注解EnableSwagger2,第二就是RequestHandlerSelectors,比较常用的就是包方式和注解方式。

package com.nan.swaggerdemo.config;

import io.swagger.annotations.ApiOperation;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nan.swaggerdemo.controller")) //扫描包下面
//                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //扫描有此注解的方法
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfoBuilder().title("Spring Boot 整合 swagger ui")
                .description("Spring Boot 整合 swagger ui项目")
                .license("MIT")
                .licenseUrl("http://opensource.org/licenses/MIT")
                .contact(new Contact("王金楠", "http://blog.youkuaiyun.com/wangjinnan16/article", "wangjinnan16@163.com"))
                .version("1.0")
                .build();
        return apiInfo;
    }

} 

  下面创建一个普通的java bean,当作我们接口的返回对象。其中注解ApiModelProperty是用来解释属性意义的,待会才接口文档里就会看到效果了。

package com.nan.swaggerdemo.model;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

/**
 * 用户信息
 */
public class User implements Serializable {

    @ApiModelProperty("用户id")
    private Long id;

    @ApiModelProperty("用户名称")
    private String name; //用户名称

    @ApiModelProperty("用户年龄")
    private Integer age; //用户年龄

    public User() {
    }

    public User(Long id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

  下面就是最重要的controller了,先看内容。

package com.nan.swaggerdemo.controller;

import com.google.common.collect.Lists;
import com.nan.swaggerdemo.model.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @ApiOperation(value = "查询用户API", notes = "按条件查询用户信息", responseContainer = "List", response = User.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pathParam", value = "url路径参数",
                    required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "queryParam", value = "普通请求参数",
                    required = true, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/users/{pathParam}", method = {RequestMethod.GET, RequestMethod.POST})
    List<User> users(@PathVariable("pathParam") String pathParam, String queryParam) {
        System.err.println("pathParam = " + pathParam);
        System.err.println("queryParam = " + queryParam);
        return Lists.newArrayList(new User(1L, "user1", 21), new User(2L, "user2", 22));
    }

}

  SpringMvc的注解就不多说了,就说说Springfox的注解,ApiOperation和ApiImplicitParam。

  ApiOperation用来说明这个接口是干什么的,还可以增加返回信息说明。

  •  value API的名字
  •  notes API的详细说明
  •  responseContainer 返回内容容器。如果然会内容有包装容器,比如本例的List,此属性只有3个值 List、Set、Map
  •  response 返回对象,class类型。对象里面的属性可以用注解ApiModeProperty来说明

  ApiImplicitParam是解释接口参数的注解,有多个可以放在ApiImplicitParams下面。
  •  name 参数的属性名
  •  value 参数的描述
  •  required boolean类型,是否必填
  •  dataType 参数数据类型,可以是原始类型或类名
  •  paramType 参数传递形式,有query、path、body、header、form,对应的就是客户端传递参数形式

三、启动项目

  代码和配置都写完了,现在启动项目,然后在浏览器访问 http://localhost:8080/swagger-ui.html,就会看到如下画面。


  可以看到swagger的配置信息都在上面,然后点List Operations,可以看到Springfox帮我们将get和post都生成了,随便点一个,例如get的,可以看到如下画面。


  可以看到,关于api的具体信息,返回信息都显示这页面上了。在参数输入框里面输入参数,然后点击Try it out,可以看到如下画面。


  在页面可以看到接口的返回内容,在后台也可以看到参数已经被正确接收。

四、总结

  经过使用来看,Springfox确实帮我们做了很多事,而且发布的项目和API文档在一起,可以直接传入参数调用,也方便测试团队去进行接口测试。这篇文档也只是入门,还有很多注解没有说到,这个就需要大家在学习和工作中慢慢尝试,谢谢。


以上就是笔者目前所学,还是很初级的内容,如果有什么错误和遗漏,还请见谅并指正,不胜感激。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值