软件编程
位置:首页>> 软件编程>> java编程>> Swagger实现动态条件注入与全局拦截功能详细流程

Swagger实现动态条件注入与全局拦截功能详细流程

作者:毕小宝  发布时间:2023-11-23 13:41:05 

标签:Swagger,动态,条件注入,全局拦截

背景

Swagger 可以提供 API 操作的测试文档,本文记录 Swagger 使用过程中遇到的两个小问题:

  • 全局响应结果进行包装后导致 Swagger 请求响应结果无法解析,如果项目中配置了 ResponseBodyAdvice 实现类,重写了 beforeBodyWrite 方法对响应结果进行统一时,应该排除 Swagger2 的两个 URL v2/api-docsswagger-resources

  • Swagger 注入条件区分测试和生产环境的配置的 ETL 不同语法对默认无配置的处理结果。

Swagger2 使用流程

Swagger 用法很简单,加入引用,一个配置就可以为应用提供接口测试界面。

第一步,引入依赖。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.0</version>
</dependency>
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.8.5</version>
</dependency>

第二步,添加 Swagger 配置类。

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnExpression("'${swagger.enable}'.equalsIgnoreCase('true')")
public class Swagger2Config {
   @Bean
   public Docket createRestApi() {
       return new Docket(DocumentationType.SWAGGER_2)
               .apiInfo(apiInfo())
               .select()
               .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
               .paths(PathSelectors.any())
               .build();
   }
   private ApiInfo apiInfo() {
       return new ApiInfoBuilder()
               .title("XXX 文档")
               .version("1.0")
               .build();
   }
}

第三步,为 Web 请求设置 Api 配置。

@GetMapping("/set")
@ApiOperation(value = "设置 Session")
public Object Index(HttpServletRequest request){
   request.getSession().setAttribute("userUid", "111111");
   return request.getSession().getAttribute("userUid");
}

条件配置分析

@ConditionalOnExpression("'${swagger.enable}'.equalsIgnoreCase('true')")

这种方式,表达式成立的条件有两项 swagger.enable 必须配置,且值为 true 时,才会成立。

另外一种写法:

@ConditionalOnExpression("${swagger.enable:true}")

如果未配置属性 swagger.enable,那么根据 ConditionalOnExpression 注解的默认值是 true ,所以就会执行注解配置。

启示录

为了方便开发测试,默认无配置时视为满足条件,生产环境下配置值为 false 是可以的。

来源:https://blog.csdn.net/wojiushiwo945you/article/details/128779434

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com