快速使用swagger2

@快速使用swagger2

swagger2的作用

在项目中,经常需要通过接口来与前端对接,对字段之类的,swagger2的出现能够有效的提示对接效率,降低沟通成本。swagger2可以在实体,类,方法,参数上添加中文注解,以标注对应的接口、字段、参数等对应的含义,前端只需要通过可视化的UI就能得到接口需要的地址、字段等信息。

1、引入jar包

<dependency>                
 <groupId>io.springfox</groupId>                
 <artifactId>springfox-swagger2</artifactId>                
 <version>3.0.0</version> 
</dependency> 

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

2、创建swagger配置类

package com.cnnc.vue.config;

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

/**
 * 接口API
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cnnc.vue.controller"))  //Controller接口输出类所在包
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 页面显示信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot使⽤Swagger2构建RESTul APIs") //显示提示语
                .description("swagger2的api")
                .termsOfServiceUrl("url")
                .contact(new Contact("","url","mail"))
                .version("1.0")
                .build();
    }
    
}

配置完成后可直接启动项目。

3、启动报错

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

解决方案:
原因: 这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。
解决:在application.properties里配置:spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER。

报404
原因:是swagger-ui版本太高了,降低springfox-swagger-ui版本:2.9.2

4、访问地址:

http://localhost:8080/swagger-ui.html

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值