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

本文介绍如何在SpringBoot项目中使用Swagger-Bootstrap-UI生成美观的API文档,包括引入依赖、配置启用及使用注解的方法,同时提供了代码示例和在线效果体验地址。

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

很简单,就三步
一是引入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/

### 若依项目中 SwaggerBootstrapUi 的集成与配置 #### 1. 添加 Maven 依赖 为了在若依项目中集成 SwaggerBootstrapUI,首先需要在 `pom.xml` 文件中添加相应的依赖项。具体来说,需引入 `springfox-swagger2` 和 `swagger-bootstrap-ui` 这两个库。 ```xml <dependencies> <!-- 引入 swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- 引入 swagger ui --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.3</version> </dependency> </dependencies> ``` 这些依赖使得 Spring Boot 应用能够支持 API 文档的自动生成以及通过 Swagger UI 来展示和测试 RESTful 接口[^4]。 #### 2. 配置 Swagger 相关属性 接着,在项目的资源文件夹下的 `application.yml` 或者 `application.properties` 中定义一些必要的参数来定制化 Swagger 行为: ```yaml # application.yml 示例片段 spring: mvc: pathmatch: matching-strategy: ant_path_matcher swagger: base-package: com.ruoyi.web.controller # 扫描的基础包路径 title: RuoYi API Documentation description: This is a sample server Petstore server. version: "0.0.1" terms-of-service-url: http://www.example.com/terms.html contact-name: Admin contact-email: admin@example.com license: Apache License Version 2.0 license-url: https://www.apache.org/licenses/LICENSE-2.0.html ``` 此部分设置允许开发者指定哪些控制器类会被扫描并纳入到最终生成API文档之中;同时也提供了有关服务的一些元数据信息给访问者查看[^5]。 #### 3. 创建 SwaggerConfig 类 最后一步是在 Java 代码层面编写一个名为 `SwaggerConfig.java` 的配置类用于启动时初始化 Swagger 组件实例,并注册 Docket Bean 实现对接口文档的支持功能。 ```java 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 SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ruoyi.web.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("RuoYi API Documentation") .description("This is a sample server Petstore server.") .termsOfServiceUrl("http://www.example.com/terms.html") .contact(new Contact("Admin", "", "admin@example.com")) .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html") .version("0.0.1") .build(); } } ``` 这段代码实现了对 Swagger 功能模块的基本配置,包括但不限于接口描述、版本号、联系人等细节内容。当应用程序运行起来之后,就可以通过浏览器访问 `/doc.html` 路径来浏览由 Swagger Bootstrap UI 提供的良好用户体验界面了[^1]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值