Swagger2

什么是Swagger2?

swagger是一个RESTFUL 接口的文档在线自动生成和功能测试的框架

Swagger2有什么作用?

写出高质量高效率的API文档

如何在Springboot中使用Swagger2

1.首先先创建一个SpringBoot项目

2.在pom.xml中添加依赖

<!-- Swagger API文档 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

  3.添加Swagger2配置类SwaggerConfig
     注1:修改扫描包名
     注2:启动类依次加上注解
@MapperScan("com.zking.swaggerdemo.mapper")
@EnableSwagger2
@ComponentScan("com.zking.swaggerdemo.utils")
   4.API接口编写
   5.SpringBoot启动成功后,访问 http://localhost:8080/swagger-ui.html 即可

3.swagger2常用注解  
@Api:用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiImplicitParams : 用在方法上包含一组参数说明。
@ApiImplicitParam:用来注解来给方法入参增加说明。
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
其中
@ApiResponse参数:

code:数字,如400
message:信息,如“参数填写错误”
response:抛出异常的类
@ApiImplicitParam参数:
paramTpye:指定参数放在哪些地方(header/query/path/body/form)
name:参数名
dataTpye:参数类型
required:是否必输(true/false)
value:说明参数的意思
defaultValue:参数默认值
   

4.Swagger在生产环境无法使用
    为了保证接口文档的安全,禁用了生产环境的加载,具体说明请看:https://sns.bladex.vip/q-39.html

    一般生产环境是不能放开swagger的,这样接口暴露在外网很不安全
一般生产环境是不能放开swagger的,这样接口暴露在外网很不安全。

定义了只有dev和test环境才会加载swagger,所以如果你部署起来需要放开端口,请把环境设置成test,prod为了安全性是强制不让开的

blade-tool的blade-core-swagger有个SwaggerAutoConfiguration配置,如下:

/**
 * swagger配置
 *
 * @author Chill
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Profile({"dev", "test"})
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration

<!-- swagger2  一个做ui 一个做提供接口的-->
      

 <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>


注1:在 Security 中的配置
Spring Boot 项目中如果集成了 Spring Security,在不做额外配置的情况下,Swagger2 文档会被拦截。
解决方法是在 Security 的配置类中重写 configure 方法添加白名单即可:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值