后端项目开发:集成接口文档(swagger-ui)

swagger集成文档具有功能丰富、及时更新、整合简单,内嵌于应用的特点。

由于后台管理和前台接口均需要接口文档,所以在工具包构建BaseSwaggerConfig基类。

1.引入依赖

java 复制代码
 <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>

2.需要添加Swagger配置类。

java 复制代码
/**
 * Swagger基础配置
 */
public abstract class BaseSwaggerConfig {

    @Bean
    public Docket createRestApi() {
        SwaggerProperties swaggerProperties = swaggerProperties();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(swaggerProperties))
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getApiBasePackage()))
                .paths(PathSelectors.any())
                .build();
        if (swaggerProperties.isEnableSecurity()) {
            docket.securitySchemes(securitySchemes()).securityContexts(securityContexts());
        }
        return docket;
    }

    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
                .version(swaggerProperties.getVersion())
                .build();
    }

    private List<ApiKey> securitySchemes() {
        //设置请求头信息
        List<ApiKey> result = new ArrayList<>();
        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;
    }

    /**
     * 自定义Swagger配置
     */
    public abstract SwaggerProperties swaggerProperties();
}
  1. 将需要配置的字段提取出来,单独作为一类
java 复制代码
/**
 * Swagger自定义配置
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Builder
public class SwaggerProperties {
    /**
     * API文档生成基础路径
     */
    private String apiBasePackage;
    /**
     * 是否要启用登录认证
     */
    private boolean enableSecurity;
    /**
     * 文档标题
     */
    private String title;
    /**
     * 文档描述
     */
    private String description;
    /**
     * 文档版本
     */
    private String version;
    /**
     * 文档联系人姓名
     */
    private String contactName;
    /**
     * 文档联系人网址
     */
    private String contactUrl;
    /**
     * 文档联系人邮箱
     */
    private String contactEmail;
}
  1. 前台接口和后台管理的包的配置,只需要继承重写该类就行了
java 复制代码
/**
 * Swagger API文档相关配置
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends BaseSwaggerConfig {

    @Override
    public SwaggerProperties swaggerProperties() {
        return SwaggerProperties.builder()
                .apiBasePackage("com.example.admin")
                .title("后台管理系统")
                .description("后台相关接口文档")
                .contactName("author")
                .version("1.0")
                .enableSecurity(true)
                .build();
    }
}

接着就可以访问http://localhost:8001/swagger-ui/index.html接口文档页面了,后续可以通过swagger来测试接口。

详细配置参考:https://swagger.io/

相关推荐
阿图灵几秒前
OpenCV 阈值与模糊:全局/自适应阈值、Canny 边缘检测与三种模糊
图像处理·人工智能·python·opencv·计算机视觉·边缘检测
神仙别闹12 分钟前
基于C++ 实现 L 系统分形树
开发语言·c++
桃西西呀12 分钟前
国内金价破 1000,「涨了多少」和「该买多少」是数学问题
人工智能·python·数据分析
君顾113 分钟前
AI智能商城实战指南:从架构设计到部署落地的完整技术方案
java·开发语言·多商户
张人玉17 分钟前
茶树 NeRF(Neural Radiance Fields,神经辐射场)三维重建与数据分析可视化系统——基于神经辐射场的茶树三维重建方法实现可视化大屏
python·数据挖掘·数据分析·echarts·three.js
脉动数据行情119 分钟前
Python WebSocket 国内商品期货|螺纹钢 & 铁矿石实时行情监听
开发语言·python·websocket
AI行业应用研究28 分钟前
2026年主流报名工具测评报告:眨眼猫会务智能体报名小程序为何成为多场景首选?
java·开发语言·小程序
额额额对了31 分钟前
Linux C 多线程编程基础:从内存模型到生命周期管理
linux·开发语言·算法
circuitsosk42 分钟前
智能体任务拆解与执行:基于ReAct+Plan-and-Execute框架的行业Skill构建实录
前端·javascript·python·react.js·react·llm agent·智能体编排
麻雀飞吧44 分钟前
近期量化工具怎么选,先看你卡在哪一环
人工智能·python