spring boot集成swagger

Updated on in 程序人生 with 0 views and 0 comments

一、依赖管理

1.1 引入依赖版本

在pom文件的properties标签中添加

<swagger.version>2.9.2</swagger.version>

1.2 引入依赖

在bs-boot-system中添加依赖

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

二、配置

2.1 代码配置

新增config包,在config包下新增配置类SwaggerConfig.java,在类中配置扫描标注了Api和方法上标注了ApiOperation注解的资源

package cn.com.wenyl.bs.config;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
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;

/**
 * @author Swimming Dragon
 * @description: 胚子swagger
 * @date 2023年12月04日 14:27
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())  // 设置API信息
                .select()  // 选择要暴露的API接口路径和请求方法
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())  // 选择要暴露的API接口路径和请求方法
                .build();  // 构建Swagger文档对象,用于生成接口文档和UI界面
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()  // 创建API信息对象,用于设置API基本信息和描述等
                .title("black-shop")  // 设置标题
                .description("black-shop接口信息")  // 设置描述
                .version("1.0")  // 设置版本号
                .contact(new Contact("Swimming Dragon", "www.wenyoulong.com", "3424675994@qq.com"))  // 设置联系信息(可选)
                .build();  // 构建API信息对象,生成接口文档和UI界面时会显示这些信息
    }
}

2.2 yml配置

在bs-boot-system的application-dev.yml配置文件中新增

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

标题:spring boot集成swagger
作者:wenyl
地址:http://www.wenyoulong.com/articles/2023/12/04/1701678252392.html