SpringBoot项目使用swagger

主要需求是使用swagger来查看api接口,感觉看起来更为直观,整理api文档也方便

话不多说,开整
项目springboot版本为:2.6.7

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>
  1. pom文件添加依赖
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

推荐方式:直接在pom文件的节点下的中手动输入springfox-swagger-ui和springfox-swagger2,在弹出的列表回车进行选择,就会自动匹配groupId和version。
2. 在文件夹新建配置类,最好放在专门的配置类文件夹,这样项目结构比较整洁,复制如下代码,导入包

@Configuration
@EnableSwagger2
public class Swagger2Configure {
    
    
    @Bean
    public Docket createRestApi() {
    
    
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xinfeng.inspect.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder().title("springboot利用swagger构建api文档")
                .description("项目描述")
                .termsOfServiceUrl("项目示例地址")
                .version("1.0")
                .build();
    }
}
  1. 这样启动项目会报错,Failed to start bean ‘documentationPluginsBootstrapper’,是因为:Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
    解决方案:
    在application.yml文件进行配置:
    spring:
    mvc:
    pathmatch:
    matching-strategy: ant_path_matcher
    在这里插入图片描述
    4.现在就可以正常启动项目了,在浏览器输入地址,因为我的项目运行在8081端口,进行替换就行
    http://localhost:8081/swagger-ui.html
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44019553/article/details/125660166
今日推荐