Spring Boot整合Swagger2

本章介绍SpringBoot整合Swagger2实现Restful API   项目中使用mysql+jpa+swagger2   步骤1:引入依赖,在pom文件中引入swagger2的相关依赖,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.misu</groupId>
    <artifactId>springboot-swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springboot-swagger2</name>
    <description>SpringBoot整合Swagger2</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <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>

        <!-- jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
步骤2:配置文件application.properties,配置如下:
#端口号
server.port=8080

#数据库
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
  步骤3:Swagger2配置类
package com.misu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * swagger2配置类
 * @author Tiramisu
 * @version 1.0.0
 * @since 2021/10/19 17:33
 **/
@Configuration
@EnableSwagger2 // 开启Swagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.misu"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot整合Swagger2")
                .description("Swagger2构建Restful Api")
                .termsOfServiceUrl("http://localhost:8080/")
                .version("2.0")
                .build();
    }

}
步骤4:User实体类
package com.misu.entity;

import com.sun.istack.internal.NotNull;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author Tiramisu
 * @version 1.0.0
 * @since 2021/10/19 17:45
 **/
@Entity
@ApiModel(description="user")
public class User {

    @Id
    @GeneratedValue
    @ApiModelProperty(value = "主键", hidden = true)
    int id;

    @ApiModelProperty(value = "用户名称")
    @Column
    @NotNull
    String userName;

    @ApiModelProperty(value = "用户密码")
    @Column
    String userPassword;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public User() {
    }

    public User(String userName, String userPassword) {
        this.userName = userName;
        this.userPassword = userPassword;
    }

    public User(int id, String userName, String userPassword) {
        this.id = id;
        this.userName = userName;
        this.userPassword = userPassword;
    }
}

步骤5:Repository 

package com.misu.repository;

import com.misu.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author Tiramisu
 * @version 1.0.0
 * @since 2021/10/19 17:54
 **/
public interface UserRepository extends JpaRepository<User, Integer> {
    User findById(int id);
}
步骤6:添加文档内容
package com.misu.controller;

import com.misu.entity.User;
import com.misu.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Tiramisu
 * @version 1.0.0
 * @since 2021/10/19 17:55
 **/
@RestController
@RequestMapping("/users")
@Api(value = "用户操作接口", tags = {"用户操作接口"})
public class UserController {

    @Autowired
    UserRepository userRepository;

    @ApiOperation(value = "获取用户详细信息", notes = "根据用户id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true)
    @PostMapping("/findById")
    public User findById(@RequestParam("id") int id) {
        return userRepository.findById(id);
    }
}
步骤7:启动项目,访问http://localhost:8080/swagger-ui.html,如图所示:   Spring Boot整合Swagger2Swagger2常用注解:   1、@Api:用在请求的类上,表示对类的说明(一般多用于Controller)    --参数values:该参数没什么意义,不需要配置    --参数tags:说明该类的作用,可以在UI界面上看到该信息 示例:
@Api(value = "退款查询")
  2、@ApiOperation:用在请求的方法上,说明方法的用途、作用    --参数values:说明方法的用途或标题    --参数notes:方法的备注说明 示例:
@ApiOperation(value = "用户查询", notes = "根据用户id来获取用户详细信息")
  3、@ApiImplicitParams:用在请求的方法上,表示一组参数的说明    --@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面    --参数name:参数名    --参数value:参数的汉字说明、解释    --参数required:参数是否必传    --参数paramType:参数放在哪个地方

          header -->请求参数的获取:@RequestHandler

          query -->请求参数的获取:@RequestParam

          path(用于restful接口)–> 请求参数的获取:@PathVariable

          body(不常用)

          form(不常用)

  --参数dataType:参数类型,默认String,其他值dataType="Integer"   --defaultValue:参数的默认值 示例:  
@ApiImplicitParams({
@ApiImplicitParam(name=“mobile”,value=“手机号”,required=true),
@ApiImplicitParam(name=“password”,value=“密码”,required=true),
@ApiImplicitParam(name=“age”,value=“年龄”,required=true,dataType=“Integer”)
})
@ApiImplicitParam也可以单独使用

 Spring Boot整合Swagger2

4、@ApiResponses :用在请求的方法上,表示一组响应    --@ApiResponse:用在ApiResponses中,一般用于表达一个错误的响应信息    --参数code:响应码,如400    --参数message:响应信息,如参数xxx为null    --参数response:抛出异常的类 示例:

@ApiResponses({@ApiResponse(code=400,message = “参数错误”),
    	    @ApiResponse(code=405,message = “参数缺失”)})
@ApiResponse也可以单独使用
@ApiResponse(code=400,message = “参数错误”)
5、@ApiModel:用在响应类上,表示一个返回响应数据的信息(一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)    --@ApiModelProperty:用在属性上,描述响应类的属性 示例:
@ApiModel(description="user")
public class User {

    @Id
    @GeneratedValue
    @ApiModelProperty(value = "主键", hidden = true)
    int id;

    @ApiModelProperty(value = "用户名称")
    @Column
    @NotNull
    String userName;

    @ApiModelProperty(value = "用户密码")
    @Column
    String userPassword;
}
6、@ApiParam:用在接口参数上,用于描述接口参数上信息(此注解对代码入侵比较大,建议使用@ApiImplicitParam作用在方法上,以保持代码的简洁) 示例:
public User findById(@ApiParam(name = "ID", value = "用户ID", required = true) int id) {
    return userRepository.findById(id);
}

上一篇:swagger2注解


下一篇:java swagger2