java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Swagger动态条件注入

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

作者:毕小宝

这篇文章主要介绍了Swagger实现动态条件注入与全局拦截功能详细流程,Swagger 可以提供 API 操作的测试文档,本文记录 Swagger 使用过程中遇到的小问题

背景

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

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 是可以的。

到此这篇关于Swagger实现动态条件注入与全局拦截功能详细流程的文章就介绍到这了,更多相关Swagger动态条件注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文