SpringBoot整合Swagger2接口文档

在项目中如果对外提供接口,那么接口文档的非常有必要的,是对接人员了解接口的唯一途径。如果接口文档写得不好,对接人员是非常痛苦的。而对于开发人员来说,写好文档本来是一件比较困难的事情。在SpringBoot中我们可以使用Swagger工具自动生成接口文档,项目中使用Swagger的注解可以自动生成标准的接口文档并且可以通过swagger ui测试接口。解决了开发人员写接口文档的难题,同时让对接人员可以快速的测试和集成接口。

官方说明文档:http://springfox.github.io/springfox/docs/2.9.2/#getting-started

此文基于版本2.9.2,当前(2020-09-17)最新的版本为3.0,3.0的配置与2.9.2有较大的区别,各位同学请注意。

 

引入依赖

maven项目在pom.xml文件中加入2.9.2的依赖:

        <!-- swagger -->
        <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.2</version>
        </dependency>

配置Swagger2

新建SwaggerConfig配置类,通过注解@Configuration注册为Bean让spring管理,通过注解@EnableSwagger2开启Swagger2接口文档:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${swagger2.enable:true}")
    private boolean enable;

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title("****系统接口文档标题") 
                .description("****系统接口文档简介")
                .version("版本1.0")
                .termsOfServiceUrl("http://www.mysite.com/termsofservice") // 服务条款网页Url
                .contact(new Contact("张三", "http://www.zhangsan.com", "zhangsan@email.com")) // 联系人信息
                .license("Apache 2.0") // license许可协议
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") // license许可协议Url
                .build();
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .select()
                .paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes())
                // 是否开启接口文档,如果是内部项目,项目上线可以设置为false关闭
                .enable(enable);
    }

    private List<ApiKey> securitySchemes() {
        //设置请求头信息
        List<ApiKey> result = new ArrayList<>();
        //设置JWT的header参数key信息
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> result = new ArrayList<>();
        result.add(getContextByPath("/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String pathRegex){
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(pathRegex))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }
}

运行项目,通过 http://localhost:{port}/swagger-ui.html访问接口文档,如下图所示:

配置Token传递

如果项目使用Spring Security,那么带权限认证的接口为了能够正常测试,swagger-ui中的接口需要带token才能测试。在上面配置类中的createRestApi方法我们通过配置 .securityContexts(securityContexts()).securitySchemes(securitySchemes()) 设置全局的header,在swagger-ui.html页面,设置token后,测试的时候所有的接口请求的时候都会带上token。

 Spring Security放行接口文档配置

如果项目使用Spring Security,那么如果不做额外配置,Swagger2文档会被拦截,此时需要在Spring Security的配置类放行swagger接口文档相关url才能正常访问,在Spring Security中重写configure方法忽略swagger相关地址:

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 过滤地址,地址不走 Spring Security 过滤器链
        web.ignoring()
                // 放行swagger相关请求
                .antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html**", "/webjars/**");
    }

配置是否启用UI

如果是公司内部项目,当项目上线后并不希望公开接口文档,那么我们可以将createRestApi方法中的Docket的enable设置为false关闭接口文档(默认开启),可以通过application.yml配置关闭。

    @Value("${swagger2.enable:true}")
    private boolean enable;


    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .select()
                .paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes())
                .enable(enable);
    }

Swagger注解使用

常用的Swagger注解有如下这些(参考其他网友的总结),在控制器类上、接口方法上、接口参数上、接口相关对象类上使用Swagger注解可以是接口文档更详细更丰富。

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
 
 
@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
 
 
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值
 
 
@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
 
 
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

SpringBoot项目中整合Swagger2接口文档,大大提高了前后端分离项目的开发效率。后端可以先把接口定义好(暂时不开放业务逻辑),前端根据swagger上定义好的接口开发页面,不用等后端接口开发完或者文档整理好后才开发对应的页面功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现springboot整合swagger2 3.0.0版本,你需要按照以下步骤操作: 1. 创建一个maven项目并引入spring-boot-starter-web和springfox-boot-starter依赖。在pom.xml文件中添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- <version>2.5.6</version> --> <!-- <version>2.6.3</version> --> <!-- <version>2.6.5</version> --> <version>2.7.3</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.26</version> </dependency> ``` 2. 在application.yml配置文件中添加以下内容: ```yaml spring: mvc: pathmatch: matching-strategy: ant_path_matcher ``` 3. 创建启动类,并在其中添加`@EnableSwagger2`注解。例如: ```java @SpringBootApplication @EnableSwagger2 public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 这样就完成了springboot整合swagger2 3.0.0版本的配置。你可以根据需要在项目中编写相应的接口文档注解以及其他相关配置。如果需要更详细的操作步骤和示例代码,你可以参考中提供的链接。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Springboot整合Swagger2(3.0.0版本)](https://blog.csdn.net/mo_sss/article/details/130820204)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Springboot整合Swagger UI 3.0.0 版本](https://blog.csdn.net/qq_42102911/article/details/126410050)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值