Springboot集成Swagger3详细操作步骤

目录

1、添加依赖

2、添加配置文件resources\config\swagger.properties

3、编写Swagger3Config配置类

4、编写Ctronller类

5、启动访问地址:

6、Swagger3常用注解说明


1、添加依赖

<!-- 引入swagger3包 -->    
 <dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-boot-starter</artifactId>
	<version>3.0.0</version>
</dependency>

<!-- 引入swagger-bootstrap-ui包,优化UI页面,可不加 -->
<dependency>
	<groupId>com.github.xiaoymin</groupId>
	<artifactId>swagger-bootstrap-ui</artifactId>
	<version>1.8.5</version>
</dependency>

2、添加配置文件resources\config\swagger.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=广东深圳

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<RequestParameter> getGlobalRequestParameters() {
        List<RequestParameter> 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<Response> getGlobalResonseMessage() {
        List<Response> 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;
    }
}

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;
    }

}

5、启动访问地址:

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

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

6、Swagger3常用注解说明

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

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

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

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

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

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

@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){

@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;

}

@ApiResponses和@ApiResponse

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

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

  • 1
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring Boot集成Swagger详细步骤与配置: 1. 在pom.xml文件中添加Swagger依赖 ``` <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配置类 创建一个SwaggerConfig类,并使用@EnableSwagger2注解开启Swagger功能。在Swagger配置类中,可以设置Swagger的一些基本信息,比如API文档的标题、描述、版本等。 ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } } ``` 3. 配置Swagger UI 在application.properties文件中添加以下配置,以开启Swagger UI: ``` #Swagger UI springfox.documentation.swagger-ui.enabled=true springfox.documentation.swagger-ui.path=/swagger-ui.html ``` 4. 配置Swagger注解 在Controller层的方法上添加Swagger注解,以便生成API文档。常用的Swagger注解有: - @Api:用于修饰Controller类,表示这个类是Swagger资源; - @ApiOperation:用于修饰Controller类中的方法,表示一个HTTP请求的操作; - @ApiParam:用于修饰方法中的参数,表示对参数的描述; - @ApiImplicitParam:用于修饰方法中的参数,表示一个请求参数的配置信息; - @ApiModel:用于修饰响应类,表示一个返回响应的信息,比如响应的数据模型; - @ApiModelProperty:用于修饰响应类中的属性,表示对属性的描述。 例如: ``` @RestController @Api(value = "用户管理", tags = "用户管理API", description = "用户管理相关接口") public class UserController { @ApiOperation(value = "获取用户列表", notes = "获取所有用户信息") @GetMapping("/users") public List<User> getUserList() { // ... } @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // ... } } ``` 5. 运行程序并访问Swagger UI 启动Spring Boot项目后,在浏览器中输入http://localhost:8080/swagger-ui.html,即可访问Swagger UI界面。在该界面中,可以查看API接口的详细信息、测试API接口等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值