• springboot如何集成swagger,swagger如何为所有API添加token参数,swagger常用注解,简介明了,举例说明


    springboot集成swagger

    如何使用swagger生成Web API

    1.在pom文件中添加如下依赖

    
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.8.0version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.8.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2.创建swagger配置

    package com.yangjunbo.helloword.properties;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class Swagger2Config implements WebMvcConfigurer {
        //指定需要扫描的包路径
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
        //编辑网站信息,如网站的标题、网站的描述、使用的协议等。
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Spring Boot中使用Swagger2构建RESTful APIs")
                    .description("Spring Boot相关文章请关注:https://www.cnblogs.com/zhangweizhong")
                    .termsOfServiceUrl("https://www.cnblogs.com/zhangweizhong")
                    .contact("架构师精进")
                    .version("1.0")
                    .build();
        }
        /**
         *  swagger增加url映射
         * @param registry
         */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
    
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    3.在controller类上添加注解说明

    package com.yangjunbo.helloword.controller;
    
    import com.yangjunbo.helloword.common.JSONResult;
    import com.yangjunbo.helloword.pojo.User;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    
    @Api(tags={"用户接口"})
    @RestController
    public class UserController {
    
        @ApiOperation(value = "创建用户",notes="根据user对象创建用户")
        @PostMapping(value = "user")
        public JSONResult save(@RequestBody User user){
            System.out.println("用户创建成功"+user.getName());
            return JSONResult.ok(201,"用户创建成功");
    
        }
    
        @ApiOperation(value = "更新用户信息",notes="根据ID来指定更新对象,并根据传过来的user信息来更新用户信息")
        @PutMapping(value = "user")
        public JSONResult update(@RequestBody User user) {
            System.out.println("用户修改成功:"+user.getName());
            return JSONResult.ok(203,"用户修改成功");
        }
    
        @ApiOperation(value = "删除用户信息",notes="根据URL中的ID指定删除对象")
        @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
        @DeleteMapping("user/{userId}")
        public JSONResult delete(@PathVariable String userId) {
            System.out.println("用户删除成功:"+userId);
            return JSONResult.ok(204,"用户删除成功");
        }
    
        @ApiOperation(value = "获取用户信息",notes="根据URL中的ID获取指定对象")
        @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
        @GetMapping("user/{userId}")
        public JSONResult queryUserById(@PathVariable String userId) {
            User user =new User();
            user.setName("weiz");
            user.setAge(20);
            System.out.println("获取用户成功:"+userId);
            return JSONResult.ok(200,"获取用户成功",user);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    4.启动项目,访问swagger主页,http://localhost:8080/swagger-ui.html

    在这里插入图片描述

    5.使用 try it out 测试接口

    在这里插入图片描述在这里插入图片描述

    6.为所有API添加token参数

    修改上面的swagger配置类中的creatRestApi方法,如下

    		@Bean
        public Docket createRestApi() {
    
            //添加请求参数,这里把token作为请求头参数传入后端
            ParameterBuilder parameterBuilder = new ParameterBuilder();
            List<Parameter> parameterList = new ArrayList<Parameter>();
            parameterBuilder.name("token").description("token令牌").modelRef(new ModelRef("String")).parameterType("header")
                    .required(false).build();
            parameterList.add(parameterBuilder.build());
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .globalOperationParameters(parameterList);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    重新启动项目,再次访问swagger主页,发现API已经支持添加token参数了,swagger会自动把token参数放到请求头中
    在这里插入图片描述

    7.swagger常用注解

    在这里插入图片描述

    参考书籍:springboot从入门到实战-章为忠编著

  • 相关阅读:
    MWM触摸屏工控机维修TEM-EV0 EN00-Z312yy-xx
    Mysql中常见的锁
    当添加一个键值对元素时,HashMap发生了什么?
    利用STM32 HAL库实现USART串口通信,并通过printf重定向输出“Hello World“
    当我点击桌面App的图标时发生了什么-浅析Activity启动流程(代码基于Android-12)
    精品Python宠物领养网站系统失物招领
    32位增强型低功耗Cortex-M3单片机CH32F203C8T6
    刷题-买卖股票的最佳时机-C++/java(暴力法,动态规划,单调栈等)
    基于JAVA疫情下居家隔离服务系统计算机毕业设计源码+系统+数据库+lw文档+部署
    【Linux常用命令10】用户管理和文件权限命令
  • 原文地址:https://blog.csdn.net/Rockandrollman/article/details/127819040