SpringBoot-2.3.4集成Swagger3(gradle)

版本环境

java:jdk-14.0.1
springboot:v2.3.4.RELEASE
gradle:gradle-6.7-rc-4
springfox(swagger):version: '3.0.0'
swagger-bootstrap-ui:version: '1.9.6'
IntelliJ IDEA:2020.1.2

swagger的配置

前后端分离的项目,接口文档的存在十分重要。与手动编写接口文档不同,swagger是一个自动生成接口文档的工具,在需求不断变更的开发环境下,手动编写文档的效率实在太低。与新版的swagger3相比swagger2配置更少,使用更加方便。

一、build.gradle文件中引入Swagger3依赖

//swagger3依赖 本次使用的是最新版的Swagger3,swagger已整合到springfox中去,在依赖引入时更方便
compile group: 'com.github.xiaoymin', name: 'swagger-bootstrap-ui', version: '1.9.6'
//swagger-bootstrap-ui依赖 引入此依赖可以试swagger节目更美观且使用方便
compile group: 'com.github.xiaoymin', name: 'swagger-bootstrap-ui', version: '1.9.6'

二、Application上面加入@EnableOpenApi注解

package com.insentek.gradlespringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

/**
 * @author lizechen
 */
@SpringBootApplication
@EnableOpenApi
public class GradleSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(GradleSpringBootApplication.class, args);
    }

}

三、Swagger3Config的配置


package com.insentek.gradlespringboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * @author zechen.li
 * @since 2020/10/12
 */
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .build()
                .securitySchemes(security());
    }
    private List<SecurityScheme> security() {
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        return Collections.singletonList(apiKey);
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("zechen.li TestDemo")
                .description("gradle springboot swagger")
                .version("1.0")
                .build();
    }
}

四、swagger-bootstrap-ui的配置

package com.insentek.gradlespringboot.config;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.spring.web.SpringfoxWebMvcConfiguration;

/**
 * @author zechen.li
 * @since 2020/10/12
 */
@SpringBootApplication
@ConditionalOnClass(SpringfoxWebMvcConfiguration.class)
public class WebMvcConfig  implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

注解使用说明

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

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

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

使用实例

controller层
package com.insentek.gradlespringboot.controller;

import com.insentek.gradlespringboot.domain.User;
import com.insentek.gradlespringboot.service.LoginService;
import com.insentek.gradlespringboot.service.impl.LoginServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zechen.li
 * @since 2020/10/13
 */
@Api(value = "api/v1/dev/login")
@RestController
@RequestMapping(value ="api/v1/dev/login")
public class LoginController {

    @Autowired
    LoginService service;

    @ApiOperation(value = "登录", notes = "使用用户名密码登录,返回实体即为登录成功,未返回实体即登录失败")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", dataType = "string", paramType = "query", required = true),
            @ApiImplicitParam(name = "pass", value = "密码", dataType = "string", paramType = "query", required = true),
    })
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public User selectVendorCount(@RequestParam(value = "name", required = true) String name,@RequestParam(value = "pass", required = true) String pass) {
        return service.check(name,pass);
    }
}

domain层/model层

package com.insentek.gradlespringboot.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zechen.li
 * @since 2020/10/13
 */
@NoArgsConstructor
@Data
@ApiModel(value = "用户实体", description = "用户实体类")
public class User {

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

    @ApiModelProperty(value = "用户密码")
    private String pass;
}

接口文档和测试界面

编译运行后访问http://localhost:8080/doc.html

Spring Boot是一个用于创建独立的、基于Spring的应程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更快地构建高效的应用程序。 MyBatis是一个开源的持久层框架,它可以将SQL语句和数据库操作映射到Java对象中,使得开发人员可以通过简单的配置来实现数据访问层的操作。在Spring Boot中集成MyBatis可以通过添加相应的依赖和配置来实现。 PageHelper是一个用于实现分页功能的MyBatis插件。它可以通过拦截SQL语句并自动添加分页查询的相关信息,从而简化了分页查询的操作。在Spring Boot中集成PageHelper可以通过添加相应的依赖和配置来实现。 Swagger是一个用于生成、描述、调用和可视化RESTful风格的Web服务的工具集。它可以根据代码注解自动生成接口文档,并提供了一个用户友好的界面来测试和调试接口。在Spring Boot中集成Swagger可以通过添加相应的依赖和配置来实现。 下面是集成Spring Boot、MyBatis、PageHelper和Swagger的步骤: 1. 在pom.xml文件中添加Spring Boot、MyBatis、PageHelper和Swagger的依赖: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- PageHelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> </dependency> <!-- 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> </dependencies> ``` 2. 在application.properties或application.yml文件中配置数据库连接和MyBatis的相关配置: ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # MyBatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.model # PageHelper配置 pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true # Swagger配置 swagger.enabled=true ``` 3. 创建MyBatis的Mapper接口和对应的XML文件,定义数据库操作的SQL语句和映射关系。 4. 创建Spring Boot的Controller类,定义接口的请求路径和处理方法。 5. 在启动类上添加@EnableSwagger2注解,启用Swagger。 ```java @SpringBootApplication @EnableSwagger2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 6. 启动应用程序,访问http://localhost:8080/swagger-ui.html可以查看生成的接口文档,并进行接口的测试和调试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值