SpringBoot整合Swagger2

前言

前后端分离后,维护接口文档基本上是必不可少的工作。Swagger2 就是接口测试工具之一,至于其他类似功能但是却收费的软件,这里就不做过多介绍了。本文主要和大伙来聊下 在Spring Boot 中如何整合 Swagger2。

导入依赖

当然,首先是创建一个 Spring Boot 项目,加入 web 依赖,创建成功后,加入两个 Swagger2 相关的依赖,完整的依赖如下:

<!--        swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
<!--        ui界面-->        
		<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
<!--        更适合国人的界面,与上面的swagger-ui二选一-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>

创建Swagger2 配置类

Swagger2 的配置也是比较容易的,在项目创建成功之后,只需要开发者自己创建一个Bean作为配置类(建议使用配置类而不是写在配置文件里),如下:

注意修改包路径

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

@Configuration
@EnableSwagger2
public class SwaggerConfig{
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
        .pathMapping("/")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example"))//包路径
        .paths(PathSelectors.any())
        .build().apiInfo(new ApiInfoBuilder()
            .title("SpringBoot整合Swagger")
            .description("SpringBoot整合Swagger,详细信息......")
            .version("9.0")
            .contact(new Contact("啊啊啊啊","blog.csdn.net","aaa@gmail.com"))
            .license("The Apache License")
            .licenseUrl("http://www.javaboy.org")
            .build());
    }
}

各参数配置含义如下:

  • swagger.title:标题
  • swagger.description:描述
  • swagger.version:版本
  • swagger.license:许可证
  • swagger.licenseUrl:许可证URL
  • swagger.termsOfServiceUrl:服务条款URL
  • swagger.contact.name:维护人
  • swagger.contact.url:维护人URL
  • swagger.contact.email:维护人email
  • swagger.base-package:swagger扫描的基础包,默认:全扫描
  • swagger.base-path:需要处理的基础URL规则,默认:/**

启动项目

此时启动项目,输入 http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:(如果是bootstrap-ui则访问http://localhost:8080/doc.html)
在这里插入图片描述

创建接口

接下来就是创建接口了,Swagger2 相关的注解其实并不多,而且很容易懂,下面我来分别向小伙伴们举例说明:

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
publicclassUserController{
    @PostMapping("/")
    @ApiOperation("添加用户的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
        @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
        })
    public RespBean addUser(String username, @RequestParam(required = true) String address) {
    	return new RespBean();
    }
    @GetMapping("/")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id){
        User user = new User();
        user.setId(id);
    	return user;
    }
    @PutMapping("/{id}")
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user){
    	return user;
    }
}

这里边涉及到多个 API,分别说明:

  1. @Api 注解可以用来标记当前 Controller 的功能。

  2. @ApiOperation 注解用来标记一个方法的作用。

  3. @ApiImplicitParam 注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。

  4. 如果有多个参数,则需要使用多个 @ApiImplicitParam 注解来描述,多个 @ApiImplicitParam 注解需要放在一个 @ApiImplicitParams 注解中。

  5. 需要注意的是,@ApiImplicitParam 注解中虽然可以指定参数是必填的,但是却不能代替 @RequestParam(required = true) ,前者的必填只是在 Swagger2 框架内必填,抛弃了 Swagger2 ,这个限制就没用了,所以假如开发者需要指定一个参数必填, @RequestParam(required = true) 注解还是不能省略。

  6. 如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中。例如下面一段代码:

    @ApiModel
    publicclassUser{
        @ApiModelProperty(value = "用户id")
        private Integer id;
        @ApiModelProperty(value = "用户名")
        private String username;
        @ApiModelProperty(value = "用户地址")
        private String address;
        //getter/setter
    }
    

使用Swagger

好了,经过如上配置之后,接下来,进入 http://localhost:8080/swagger-ui.html,可以看到如下效果:

(如果是bootstrap-ui则访问http://localhost:8080/doc.htm)

在这里插入图片描述

在 Security 中的配置

如果我们的 Spring Boot 项目中集成了 Spring Security,那么如果不做额外配置,Swagger2 文档可能会被拦截,此时只需要在 Spring Security 的配置类中重写 configure 方法,添加如下过滤即可:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/swagger-ui.html")
            .antMatchers("/v2/**")
            .antMatchers("/swagger-resources/**");
}

如此之后,Swagger2 文件就不需要认证就能访问了。不知道小伙伴们有没有看懂呢?有问题欢迎留言讨论。

@ApiModel和@ApiModelProperty用法

@ApiModel

使用场景:在实体类上边使用,标记类是swagger的解析类。

概述:提供有关swagger模型的其它信息,类将在操作中用作类型时自动内省。
在这里插入图片描述

@ApiModelProperty

使用场景:使用在被 @ApiModel 注解的模型类的属性上。表示对model属性的说明或者数据操作更改 。

概述:添加和操作模型属性的数据。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笼中小夜莺

嘿嘿嘿,请用金钱尽情地蹂躏我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值