Swagger的使用教程

news2025/5/24 19:53:35

Swagger简介

Swagger是一个规范和完整的API框架,可用于生成、描述、调用Restful风格的Web服务的接口文档。如果你在SpringBoot中使用的话,在项目启动后可以自动生成在线可调用的API文档,非常方便!

在SpringBoot中集成

首先在pom.xml引入依赖

<!--springfox swagger官方Starter-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

在apllication中配置文件

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER

增加一个兼容性Bean的控制

添加Swagger的Java配置,配置好Api信息和需要生成接口文档的类扫描路径,注意在SpringBoot2.6.x以上版本整合时由于兼容性问题需要配置一个BeanPostProcessor的Bean;

/**
 * @description Swagger相关配置
 */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerUI演示")
                .description("mall-tiny")
                .contact(new Contact("macro", null, null))
                .version("1.0")
                .build();
    }

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

访问地址

访问API文档信息,访问地址:http://localhost:8088/swagger-ui/
就可以看到具体的信息

开始使用

相关注解

在这里插入图片描述

相关配置

以下是它的一些常用配置

springfox:
  documentation:
    # 是否启用Swagger扫描代码生成文档
    enabled: true
    open-api:
      # 是否启用Swagger的open-api
      enabled: false
    swagger-ui:
      # 是否启用Swagger的Web UI
      enabled: true
      # 配置文档基础路径,此时路径为:/doc/swagger-ui/index.html
      base-url: /doc

基本使用

使用时我们只需把Swagger对应的注解添加到接口方法上即可

1.@Api

value:简要描述该类的作用。
tags:用于给 API 进行分组,通常用于 UI 界面展示。

@Api(value = "用户管理接口", tags = {"用户管理"})  
public class UserController {  
    // ...  
}

2.@ApiOperation

value:简要描述该操作的主要功能。
notes:对该操作的详细说明或注意事项。

@ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户详细信息")  
@GetMapping("/users/{id}")  
public ResponseEntity<User> getUserById(@PathVariable String id) {  
    // ...  
}

3. @ApiModel

实体类上的注解

@ApiModel(value = "PmsBrand",description = "商品品牌")
public class PmsBrand implements Serializable {
    @ApiModelProperty(value = "主键ID")
    private Long id;

    @ApiModelProperty(value = "名称")
    private String name;

    @ApiModelProperty(value = "首字母")
    private String firstLetter;

    @ApiModelProperty(value = "排序")
    private Integer sort;

    @ApiModelProperty(value = "是否为品牌制造商:0->不是;1->是")
    private Integer factoryStatus;

    @ApiModelProperty(value = "是否显示")
    private Integer showStatus;

    @ApiModelProperty(value = "产品数量")
    private Integer productCount;

    @ApiModelProperty(value = "产品评论数量")
    private Integer productCommentCount;

    @ApiModelProperty(value = "品牌logo")
    private String logo;

    @ApiModelProperty(value = "专区大图")
    private String bigPic;

    @ApiModelProperty(value = "品牌故事")
    private String brandStory;
}

结合Spring Security使用

我们经常会在项目中使用Spring Security实现登录认证,接下来我们来讲下如何使用Swagger整合Spring Security,实现访问需要登录认证的接口。

如何访问需要登录认证的接口?只需在访问接口时添加一个合法的Authorization请求头即可,下面是Swagger相关配置

/**
 * @description Swagger相关配置(带认证)
 */
@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller"))
                .paths(PathSelectors.any())
                .build()
                //添加登录认证
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<SecurityScheme> securitySchemes() {
        //设置请求头信息
        List<SecurityScheme> 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("/brand/.*"));
        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;
    }
}

我们需要在Spring Security中配置好Swagger静态资源的无授权访问,比如首页访问路径/swagger-ui/

/**
 * @auther macrozheng
 * @description SpringSecurity的配置
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Lazy
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf
                .disable()
                .sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问
                        "/",
                        "/swagger-ui/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**"
                )
                .permitAll()
                .antMatchers("/admin/login")// 对登录注册要允许匿名访问
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
        return httpSecurity.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> {
            AdminUserDetails admin = adminService.getAdminByUsername(username);
            if (admin != null) {
                return admin;
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1593409.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

797. 所有可能的路径

给你一个有 n 个节点的 有向无环图&#xff08;DAG&#xff09;&#xff0c;请你找出所有从节点 0 到节点 n-1 的路径并输出&#xff08;不要求按特定顺序&#xff09; graph[i] 是一个从节点 i 可以访问的所有节点的列表&#xff08;即从节点 i 到节点 graph[i][j]存在一条有向…

办公小助手来啦! Textin接口,轻松提取文件信息,让你如虎添翼!

&#x1f60e;大家是不是经常为了一堆文件而头疼呢&#xff1f;&#x1f4da;别担心&#xff0c;Textin接口它来了&#xff01;&#x1f389; 一、Textin的神秘面纱 1. Textin是谁&#xff1f; &#x1f50d;Textin接口&#xff0c;一款专业的文件信息提取工具&#xff0c;只…

Arco design 发布到生成环境F5刷新报错404

问题&#xff1a;开发环境没问题&#xff0c;生成环境正常跳转也没问题但是F5刷新报错 解决办法一&#xff1a;修改 history: createWebHistory(), 改为history: createWebHashHistory(),

微服务-6 Gateway网关

一、网关搭建 此时浏览器访问 localhost:10010/user/list 后正常返回数据&#xff0c;说明网关已生效&#xff0c;其原理流程图如下&#xff1a; 二、网关过滤器 作用&#xff1a;处理一切进入网关的请求和微服务响应。 1. 网关过滤器的分类&#xff1a; a. 某个路由的过滤器 …

C语言 | Leetcode C语言题解之第26题删除有序数组中的重复项

题目&#xff1a; 题解&#xff1a; int removeDuplicates(int* nums, int numsSize) {if (numsSize 0) {return 0;}int fast 1, slow 1;while (fast < numsSize) {if (nums[fast] ! nums[fast - 1]) {nums[slow] nums[fast];slow;}fast;}return slow; }

教程备忘 一文搞定 cmake 全部技巧之 app 和 lib 的 cmake 系统

1&#xff0c;APP cmake 1.1 hello_app_01 文件&#xff1a;hello.cpp add_impl.cpp sub_impl.cpp CMakeLists.txt hello.cpp #include <iostream> float add(float, float); float sub(float, float);int main() {float a, b;a 7.7f;b 2.333f;std::cout<&l…

Java面试之redis篇

文章目录 布隆过滤器BloomFilter布隆过滤器是什么、能干嘛原理hash冲突导致数据不精确 缓存预热缓存雪崩发生预防 缓存穿透缓存穿透是什么解决 工作中哪里使用过redis 布隆过滤器BloomFilter 布隆过滤器是什么、能干嘛 由一个初值都为零的bit数组和多个哈希函数构成&#xff…

系统架构设计图

首先明确应用架构的定义&#xff0c;从百度百科上即可了解到何为应用架构&#xff1a; 应用架构&#xff08;Application Architecture&#xff09;是描述了IT系统功能和技术实现的内容。应用架构分为以下两个不同的层次&#xff1a; 企业级的应用架构&#xff1a;企业层面的应…

SpringBoot3整合Mybatis plus

Java版本&#xff1a;17 Spring Boot版本&#xff1a;3.1.10 Mybatis plus版本&#xff1a;3.5.5 源码地址&#xff1a;Gitee仓库 01 创建我们的项目工程 首先&#xff0c;我们创建一个maven工程spring-boot3-demo&#xff0c;pom文件配置如下。 这里我们将spring-boot-start…

生成对抗网络(GAN)工作原理及应用

文章目录 1、概述2、GAN的工作原理2.1、生成器&#xff08;Generator&#xff09;2.2、判别器&#xff08;Discriminator&#xff09; 4、GAN的优点5、GAN的应用6、注意事项7、总结 1、概述 生成对抗网络&#xff08;Generative Adversarial Network&#xff0c;简称GAN&#…

JAVA实现人工智能,采用框架SpringAI

Spring AI介绍 Spring AI是AI工程师的一个应用框架&#xff0c;它提供了一个友好的API和开发AI应用的抽象&#xff0c;旨在简化AI应用的开发工序&#xff0c;例如开发一款基于ChatGPT的对话应用程序。 项目地址&#xff1a;https://github.com/spring-projects-experimental/sp…

C#泛型,利用反射创建和普通创建泛型

泛型,利用反射创建和普通创建 反射 var input Activator.CreateInstance(typeof(Input<>).MakeGenericType(typeof(T))) as dynamic;typeof(T)这个位置可以塞入不同的类型 Activator.CreateInstance 反射动态创建实例&#xff1a; 这种方式使用 Activator.CreateIns…

【1000个GDB技巧之】如何在远端服务器打开通过vscode动态观测Linux内核实战篇?

Step: 配置ssh的服务端host &#xff08;也可以直接在vscode中配置&#xff0c;忽略&#xff09; 主要步骤&#xff1a;在~/.ssh/config中添加服务端的host&#xff0c;以便vscode的remote中能够登录 详细配置过程参考兄弟篇文章&#xff1a;ssh config如何配置用host名替代ro…

基于SpringBoot的“线上教学平台”的设计与实现(源码+数据库+文档+PPT)

基于SpringBoot的“线上教学平台”的设计与实现&#xff08;源码数据库文档PPT) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SpringBoot 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 线上教学平台结构图 管理员登录界面图 学员管理界…

【ARM 裸机】汇编 led 驱动之原理分析

1、我们为什么要学习汇编&#xff1f;&#xff1f;&#xff1f; 之前我们或许接触过 STM32 以及其他的 32 位的 MCU ,都是基于 C 语言环境进行编程的&#xff0c;都没怎么注意汇编&#xff0c;是因为 ST 公司早已将启动文件写好了&#xff0c;新建一个 STM32 工程的时候&#…

demo(四)nacosgateway(2)gatewayspringsercurity

一、思路 1、整体思路 用户通过客户端访问项目时&#xff0c;前端项目会部署在nginx上&#xff0c;加载静态文件时直接从nginx上返回即可。当用户在客户端操作时&#xff0c;需要调用后端的一些服务接口。这些接口会通过Gateway网关&#xff0c;网关进行一定的处理&#xff0…

使用云服务器搭建CentOS操作系统

云服务器搭建CentOS操作系统 前言一、购买云服务器腾讯云阿里云华为云 二、使用 XShell 远程登陆到 Linux关于 Linux 桌面下载 XShell安装XShell查看 Linux 主机 ip使用 XShell 登陆主机 三、无法使用密码登陆的解决办法 前言 CentOS是一种基于Red Hat Enterprise Linux&#…

大语言模型总结整理(不定期更新)

《【快捷部署】016_Ollama&#xff08;CPU only版&#xff09;》 介绍了如何一键快捷部署Ollama&#xff0c;今天就来看一下受欢迎的模型。 模型简介gemmaGemma是由谷歌及其DeepMind团队开发的一个新的开放模型。参数&#xff1a;2B&#xff08;1.6GB&#xff09;、7B&#xff…

Python分支结构

我们刚开始写的Python代码都是一条一条语句顺序执行&#xff0c;这种代码结构通常称之为顺序结构。 然而仅有顺序结构并不能解决所有的问题&#xff0c;比如我们设计一个游戏&#xff0c;游戏第一关的通关条件是玩家在一分钟内跑完全程&#xff0c;那么在完成本局游戏后&#x…