spring boots利用wagger-bootstrap-ui生成好看的api文档

很简单,就三步
一是引入jar包
二是启用配置
三是使用注解

在spring boots中使用swagger-bootstrap-ui

本文只记录在Spring Boot中使用swagger-bootstrap-ui的整个步骤。

简介主要简单介绍Swagger-Bootstrap-UI 和Swagger,接着说明spring boots 利用swagger-bootstrap-ui 生成好看的api文档的所有步骤,最后提供Swagger-Bootstrap-UI 代码地址和其原理详解地址。

Swagger简介

在近期前后端分离开发模式的项目中,前端不止一次的抱怨我一直在给他提供新的接口文档,为了减小接口定义沟通成本,我们决定引入Swagger。

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。

Swagger-Bootstrap-UI简介

Swagger-Bootstrap-UI 基于Swagger 的前端UI ,采用jQuery+bootstrap实现。

因Swagger 的默认UI 是上下结构的,用起来不太习惯,所以用Swagger-Bootstrap-UI 替换Swagger 默认的UI实现左右菜单风格的Swagger-UI ,让其看起来更清晰明了。

使用swagger-bootstrap-ui步骤介绍

本项目基于spring boot,IDE是idea,使用Swagger-Bootstrap-UI的步骤如下:

引入swagger和的swagger-bootstrap-ui包

		<!-- 引入swagger-ui包  -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- 引入swagger包  -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- 引入swagger-bootstrap-ui包 -->
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>swagger-bootstrap-ui</artifactId>
			<version>1.8.3</version>
		</dependency>

启用swagger

/**
 * @author xian
 * @date 2018/9/3 9:45
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {

    @Bean
    public Docket createH5RestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("h5")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.project.controller.h5"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket createPcRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("pc")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.project.controller.pc"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger RESTful APIs")
                .description("swagger RESTful APIs")
                .termsOfServiceUrl("http://www.test.com/")
                .contact("xiaoymin@foxmail.com")
                .version("1.0")
                .build();
    }

	//添加ResourceHandler
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
    
}

注意
Docket:如果需要分组显示不同文件夹下的controller,可以像上面代码那样写,否则写一个Docket就好了

SpringBoot访问doc.html页面404:

第一种办法需要继承SpringBoot的WebMvcConfigurerAdapter接口,添加相关的ResourceHandler,可以像上面代码那样写

第二种办法需要实现SpringBoot的WebMvcConfigurer接口,添加相关的ResourceHandler,代码如下

@SpringBootApplication
public class SwaggerBootstrapUiDemoApplication implements WebMvcConfigurer{

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("doc.html").addResourceLocations("classpath*:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath*:/META-INF/resources/webjars/");
	}
}

本人用的第一种方法,成功访问doc.html页面

swagger2注解

给controller类添加swagger2注解的时候,打出@Api可以看到swagger2的注解如下
swagger2注解
具体使用举例说明:

  1. @Api()用于类,表示标识这个类是swagger的资源
字段说明
tags说明
value说明,可以使用tags替代
/**
 * @author xian
 * @date 2018/8/24 14:27
 */
@Api(value="用户controller",tags={"用户操作接口"})
@Controller
@RequestMapping("web/user")
public class UserController {

}
  1. @ApiOperation()用于方法,表示一个http请求的操作
字段说明
tags可以重新分组
value方法描述
notes提示内容
    @PostMapping("/userLogin")
    @ResponseBody
    @ApiOperation(value = "用户登录", tags = {"返回用户信息"}, notes = "务必提交json格式")
    public Result userLogin(@RequestBody UserLoginDto userLoginDto){
    	Result result = new Result();
        return result;
    }
  1. @ApiParam()用于方法的参数的字段说明,是否必填等
字段说明
name参数名
value参数说明
required是否必填
    @GetMapping("/userInfo")
    @ResponseBody
    @ApiOperation(value = "查询个人信息")
    public Result userInfo(@ApiParam(name="phone",value="用户手机号",required=true)String phone) {
    	Result result = new Result();
        return result;
    }
  1. @ApiModel()用于类,表示对类进行说明,用于参数用实体类接收
字段说明
value对象说明
description描述

@ApiModelProperty()用于model的字段,表示对model属性的说明或者数据操作更改

字段说明
value字段说明
name重写属性名字
dataType参数重写属性类型
example举例说明
required是否必填
hidden隐藏
/**
 * @author xian
 * @date 2018/8/28 10:33
 */
@ApiModel(description="登录请求参数")
public class UserLoginDto {

    @ApiModelProperty(value="用户电话", required=true)
    private String phone;

    @ApiModelProperty(value="密码", required=true)
    private String password;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
  1. @ApiIgnore用于类,方法,方法参数,表示这个方法或者类被忽略
/**
     * @author xian
     * @date 2018/8/27 16:02
     * 用户列表
     * @param key 关键字
     * @param start 起始时间
     * @param end 结束时间
     * @param pageNo 页码
     * @param limit 每页条数
     * @return com.example.project.common.Result
     */
    @RequestMapping("/pc/listByPage")
    @ResponseBody
    @ApiIgnore
    public Result listByPage(String key, Integer start, Integer end, int pageNo, int limit){
        Result result = new Result();
        return result;
    }
  1. @ApiImplicitParam() 用于方法,表示单独的请求参数
    @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

    这个还没用过…

  2. @ApiResponse()
    @ApiResponses() 用于方法,包含多个 @ApiResponse
    code必须与http code相对应,否则会报错

    @GetMapping("/userInfoByUserId")
    @ResponseBody
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功返回data", response = UserInfoVo.class)
    })
    public Result userInfoByUserId(String userId){
    	Result result = new Result();
        return result;
    }

返回对象响应示例如下

{
	"object1": 0,
	"object2": ""
}

如果响应参数是List,则在ApiResponse()中加上responseContainer,代码如下

    @ApiResponse(code = 200, message = "查询成功返回data", response = UserInfoVo.class, responseContainer = "List")

返回列表响应示例如下

[
    {
        "object1": 0,
        "object2": ""
    }
]

以上所有接口,如果不显示就把tags去掉或者用英文来取代中文

效果展示

主页

主页

接口

接口

响应参数

响应参数

在线调试

在这里插入图片描述

项目目前所有数据都经过加密处理了测试结果就不贴了

地址

码云地址 :https://gitee.com/xiaoym/swagger-bootstrap-ui

GitHub地址 :https://github.com/xiaoymin/Swagger-Bootstrap-UI

在线效果体验 :http://swagger-bootstrap-ui.xiaominfo.com/doc.html

swagger-bootstrap-ui详解 :http://www.xiaominfo.com/2018/08/29/swagger-bootstrap-ui-description/

  • 15
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值