• Springboot集成Swagger3详细操作步骤


    目录

    1、添加依赖

    2、添加配置文件resourcesconfigswagger.properties

    3、编写Swagger3Config配置类

    4、编写Ctronller类

    5、启动访问地址:

    6、Swagger3常用注解说明


    1、添加依赖

        
     
    	io.springfox
    	springfox-boot-starter
    	3.0.0
    
    
    
    
    	com.github.xiaoymin
    	swagger-bootstrap-ui
    	1.8.5
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、添加配置文件resourcesconfigswagger.properties

    swagger.documentation-type=oas_30
    swagger.base-package=com.example.demo.db.controller
    swagger.api-info.title=demo_springboot
    swagger.api-info.description=xxx
    swagger.api-info.contact.name=JsonFling
    swagger.api-info.contact.email=jsonfling@xxxxxxxx.com
    swagger.api-info.contact.url=广东深圳
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3、编写Swagger3Config配置类

    package com.example.demo.db.config;
    
    import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.NestedConfigurationProperty;
    import org.springframework.context.annotation.*;
    import org.springframework.http.HttpMethod;
    import org.springframework.stereotype.Component;
    import springfox.documentation.builders.*;
    import springfox.documentation.oas.annotations.EnableOpenApi;
    import springfox.documentation.schema.ScalarType;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.ResourceBundle;
    
    /**
     * 描述: 单独定义 Swagger 配置类 profile 中包含 dev,sit,uat 任意一个时才会启动 Swagger (即生产环境不启动 Swagger) 环境变量
     * SPRING_PROFILES_ACTIVE=dev/sit/uat 才启用该配置
     */
    @Configuration
    //@Profile({"dev", "test", "uat"})
    @EnableOpenApi//会自动开启配置,启动类不需要加任何注解
    @EnableSwaggerBootstrapUI//访问美化,方便查看调试
    public class Swagger3Config {
        /**
         * @return Docket是swagger全局配置对象
         */
        @Bean
        public Docket createApi(SwaggerProperties properties) {
            return new Docket(properties.getDocumentationType().value)
                    .apiInfo(createApiInfo(properties))
                    .select()
                    // 指定扫描的包,不指定会扫描出 spring 框架的接口,指定错误会导致接口扫描不出来
                    .apis(RequestHandlerSelectors
                            .basePackage(properties.getBasePackage()))
                    .paths(PathSelectors.any())
                    .build()
                    .globalRequestParameters(getGlobalRequestParameters())//加入通用入参
                    .globalResponses(HttpMethod.POST, getGlobalResonseMessage());//post方法加入通用响应头
        }
    
        /**
         * API 文档基础信息,包括标题、联系人等
         * @return ApiInfo
         */
        private ApiInfo createApiInfo(SwaggerProperties properties) {
            SwaggerApiInfo apiInfoMeta = properties.getApiInfo();
            SwaggerApiInfoContact contactMeta = apiInfoMeta.getContact();
            Contact contact = new Contact(contactMeta.getName(), contactMeta.getUrl(), contactMeta.getEmail());
            return new ApiInfoBuilder()
                    .title(apiInfoMeta.getTitle())
                    .description(apiInfoMeta.getDescription())
                    .contact(contact)
                    .build();
        }
    
        //定义文档类型,配置文件配置
        public enum DocumentationTypeMode {
            /**
             * SWAGGER_12
             */
            SWAGGER_12(DocumentationType.SWAGGER_12),
            /**
             * SWAGGER_2
             */
            SWAGGER_2(DocumentationType.SWAGGER_2),
            /**
             * OAS_30
             */
            OAS_30(DocumentationType.OAS_30);
    
            private final DocumentationType value;
    
            DocumentationTypeMode(DocumentationType value) {
                this.value = value;
            }
        }
    
        @Component
        @PropertySource(value = "classpath:/config/swagger.properties", ignoreResourceNotFound = true, encoding = "UTF-8")
        @ConfigurationProperties(prefix = "swagger")
        public static class SwaggerProperties {
    
            private DocumentationTypeMode documentationType = DocumentationTypeMode.OAS_30;
    
            private String basePackage = "com.example.demo.db.controller";
    
            private SwaggerApiInfo apiInfo = new SwaggerApiInfo();
    
            public DocumentationTypeMode getDocumentationType() {
                return documentationType;
            }
    
            public void setDocumentationType(DocumentationTypeMode documentationType) {
                this.documentationType = documentationType;
            }
    
            public String getBasePackage() {
                return basePackage;
            }
    
            public void setBasePackage(String basePackage) {
                this.basePackage = basePackage;
            }
    
            public SwaggerApiInfo getApiInfo() {
                return apiInfo;
            }
    
            public void setApiInfo(SwaggerApiInfo apiInfo) {
                this.apiInfo = apiInfo;
            }
        }
    //文档信息联系人实体类
        public static class SwaggerApiInfoContact {
            private String name;
    
            private String url;
    
            private String email;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getUrl() {
                return url;
            }
    
            public void setUrl(String url) {
                this.url = url;
            }
    
            public String getEmail() {
                return email;
            }
    
            public void setEmail(String email) {
                this.email = email;
            }
        }
        //文档信息联系人实体类
        public static class SwaggerApiInfo {
    
            private String title;
    
            private String description;
    
            @NestedConfigurationProperty
            private SwaggerApiInfoContact contact;
    
            public String getTitle() {
                return title;
            }
    
            public void setTitle(String title) {
                this.title = title;
            }
    
            public String getDescription() {
                return description;
            }
    
            public void setDescription(String description) {
                this.description = description;
            }
    
            public SwaggerApiInfoContact getContact() {
                return contact;
            }
    
            public void setContact(SwaggerApiInfoContact contact) {
                this.contact = contact;
            }
        }
    
        //生产通过接口入参
        private List getGlobalRequestParameters() {
            List parameters = new ArrayList<>();
            parameters.add(new RequestParameterBuilder()
                    .name("appid")
                    .description("平台id")
                    .required(true)
                    .in(ParameterType.QUERY)
                    .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                    .required(false)
                    .build());
            parameters.add(new RequestParameterBuilder()
                    .name("udid")
                    .description("设备的唯一id")
                    .required(true)
                    .in(ParameterType.QUERY)
                    .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                    .required(false)
                    .build());
            parameters.add(new RequestParameterBuilder()
                    .name("version")
                    .description("客户端的版本号")
                    .required(true)
                    .in(ParameterType.QUERY)
                    .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                    .required(false)
                    .build());
            return parameters;
        }
    
        //生成通用响应信息
        private List getGlobalResonseMessage() {
            List responseList = new ArrayList<>();
            responseList.add(new ResponseBuilder()
                    .code("404")
                    .description("找不到资源")
                    .build());
            responseList.add(new ResponseBuilder()
                    .code("0")
                    .description("成功")
                    .build());
            responseList.add(new ResponseBuilder()
                    .code("10")
                    .description("系统异常")
                    .build());
            responseList.add(new ResponseBuilder()
                    .code("20")
                    .description("参数错误")
                    .build());
            responseList.add(new ResponseBuilder()
                    .code("30")
                    .description("系统异常")
                    .build());
            //或者通过枚举类添加
    //        for (ResponseStatusEnum value:ResponseStatusEnum.values()) {
    //            String code = String.valueOf(value.getCode());
    //            String message =value.getMessage();
    //                    responseList.add(new ResponseBuilder().code(code).description(message);
    //        }
    
            return responseList;
        }
    }
    
    • 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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247

    4、编写Ctronller类

    package com.example.demo.db.controller;
    
    import com.example.demo.db.domain.Student;
    import io.swagger.annotations.*;
    import org.springframework.web.bind.annotation.*;
    
    @Api(tags = "学生信息Controller")
    @RestController
    @RequestMapping(value = "/Student",method = RequestMethod.GET)
    public class StudentController{
        @ApiOperation(value ="学生信息查询findAllStudent接口",notes = "注意点说明:接口通过id获取用户的详细信息,id必须传递")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
                @ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
        })
        @RequestMapping(value = "/findAllStudent")
        public Student  findAllStudent(String sid,String sname){
            return null;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    5、启动访问地址:

    http://localhost:8011/doc.html (加入UI优化依赖的访问路径)

    http://localhost:8011/swagger-ui/index.html (原始路径)

    6、Swagger3常用注解说明

    @Api:用在请求的类上,说明该类的作用

    参数:
    tags:说明这个类的作用
    value:这个参数没有什么意义,不需要配置

    @Api(tags = "学生信息Controller")
    
    • 1

    @ApiOperation:用在请求的方法上,说明方法的作用

    参数:
    value:说明方法的作用
    notes:方法的备注说明

     @ApiOperation(value ="学生信息查询findAllStudent接口",notes = "注意点说明:接口通过id获取用户的详细信息,id必须传递")
    
    • 1

    @ApiImplicitParams和@ApiImplicitParam,和@ApiParam

    (1) @ApiImplicitParams:用在请求的方法上,包含一组参数说明
    (2)@ApiImplicitParams:用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息
    参数:
    name:参数名
    value:参数的汉字说明、解释
    required:参数是否必须传
    paramType:参数放在哪个地方
    · header --> 请求参数的获取:@RequestHeader
    · query --> 请求参数的获取:@RequestParam
    · path(用于restful接口)–> 请求参数的获取:@PathVariable
    · body(不常用)
    · form(不常用)
    dataType:参数类型,默认String,其它值dataType=“Integer”
    defaultValue:参数的默认值
    (3)@ApiParam:用在方法参数里,指定对应请求参数的配置信息

     @ApiImplicitParams({
                @ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
                @ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
        })
    
    findAllStudent(@ApiParam(value = "id",name="id",required = true,defaultValue = "01") String id){
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    @ApiModel和@ApiModelProperty

    (1)@ApiModel:用于响应类上,表示一个返回响应数据的信息
    (这种一般用在post创建的时候,使用@RequestBody这样的场景,
    请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    (2)@ApiModelProperty:用在属性上,描述响应类的属性

    @ApiModel(value = "Student实体类",description = "学生实体对象")
    @Data
    public class Student implements Serializable {
        @ApiModelProperty("学生id")
        private String sid;
        @ApiModelProperty("学生姓名")
        private String sname;
        @ApiModelProperty("学生年龄")
        private Date sage;
        @ApiModelProperty("学生性别")
        private String ssex;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    @ApiResponses和@ApiResponse

    (1)@ApiResponses:用于请求的方法上,表示一组响应
    (2)@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
    code:数字,例如400
    message:信息,例如"请求参数没填好"
    response:抛出异常的类

    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    
    • 1
    • 2
    • 3
    • 4

    先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

  • 相关阅读:
    DHorse系列文章之多环境标识
    LeetCode 1123. Lowest Common Ancestor of Deepest Leaves【树,DFS,BFS,哈希表】1607
    前端自动化测试入门教程
    图像相关知识(分辨率、帧率、数据格式、数据量以及像素时钟)
    不花钱就能完美解决大型离散非标设备生产行业企业信息化
    CMMI的五个级别
    WPF利用Path自定义画头部导航条(TOP)样式
    React之Redux的使用配置
    互联网摸鱼日报(2022-10-20)
    arm day 9
  • 原文地址:https://blog.csdn.net/m0_67391683/article/details/126115805