SpringBoot整合Swagger2

一、序言:

之前开发项目前后端对接,需要手写接口文档。文档更新太多时,会经常出现遗漏,这样就会出现前后端不一致的现象。而swagger的出现很好的解决了这一现象,也大大方便了开发人员,后端开发人员在测试接口方面也得到极大的效率提升。现在就介绍下springBoot整合Swagger2。

二、springboot整合swagger2

1、依赖:

       <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

2、Swagger配置类

package com.left;

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.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * <pre>
 *     @author : orange
 *     e-mail : 495314527@qq.com
 *     time   : 2018/8/27 14:49
 *     desc   : swagger配置
 *     version: 1.0
 * </pre>
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket restApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.left.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("springboot整合swagger2")
                .description("springboot整合swagger2")
                .termsOfServiceUrl("https://blog.youkuaiyun.com/weixin_37591536")
                .version("1.0")
                .build();
    }

}

3、接口

package com.left.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.left.PageBean;
import com.left.Result;
import com.left.enums.ResultEnum;
import com.left.request.IdReq;
import com.left.request.repair.*;
import com.left.util.ResultUtils;
import com.left.web.dataObject.RepairSite;
import com.left.web.query.StatusPageQuery;
import com.left.web.service.RepairSiteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * <pre>
 *     @author : orange
 *     e-mail : 495314527@qq.com
 *     time   : 2018/7/23 10:45
 *     desc   :
 *     version: 1.0
 * </pre>
 */
@Slf4j
@RestController
@Api(description = "维修站点相关")
@RequestMapping("/repairSite")
public class RepairSiteController {

    @Reference
    private RepairSiteService repairSiteService;

    @PostMapping("/getOne")
    @ApiOperation("查询单个维修站点信息")
    public Result getOne(@RequestBody IdReq req) throws Exception {
        RepairSite one = repairSiteService.getOne(req.getId());
        return ResultUtils.success(one);
    }


    @PostMapping("/page")
    @ApiOperation("分页查询维修站点")
    public Result pageSite(@RequestBody RepairSitePageReq req) throws Exception {
        StatusPageQuery pageQuery = new StatusPageQuery();
        BeanUtils.copyProperties(req, pageQuery);
        PageBean<RepairSite> pageBean = repairSiteService.page(pageQuery);

        if (pageBean == null) {
            return ResultUtils.error(ResultEnum.NO_DATA);
        }
        return ResultUtils.success(pageBean);
    }

}

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

界面如下:

5、Swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数

 

### SpringBoot 整合 Swagger2 示例教程 在 Spring Boot 项目中整合 Swagger2,可以通过引入相关依赖并进行适当的配置来实现。以下是具体的实现步骤和代码示例: #### 1. 添加依赖 需要在项目的 `pom.xml` 文件中添加以下依赖项: ```xml <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> ``` 这些依赖分别用于生成 Swagger 文档和提供 Swagger UI 的可视化界面[^4]。 #### 2. 创建 Swagger 配置类 创建一个配置类,通过注解声明启动 Swagger 功能,并生成 `Docket` 实例: ```java 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; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot 中使用 Swagger2 API 文档") .description("更多详情请参考官方文档") .version("1.0.0") .build(); } } ``` 上述代码中,`@Configuration` 注解声明该类为配置类,`@EnableSwagger2` 注解启用 Swagger 功能(注意:如果使用的是 Swagger3,则无需此注解)。`Docket` 实例定义了 API 文档的元数据和扫描规则[^2]。 #### 3. 启动项目并访问 Swagger UI 完成以上配置后,启动 Spring Boot 项目。默认情况下,可以通过以下地址访问 Swagger UI 界面: ``` http://localhost:8080/swagger-ui.html ``` 如果使用的是 Swagger3,则访问地址可能为: ``` http://localhost:8080/swagger-ui/ ``` #### 4. 测试接口 在控制器中定义一些测试接口,例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class ExampleController { @GetMapping("/hello") public String hello() { return "Hello, Swagger!"; } } ``` 启动项目后,在 Swagger UI 界面中可以查看并测试该接口。 --- ### 注意事项 - 如果项目中启用了 `@EnableWebMvc` 或自定义了 `WebMvcConfigurer`,可能会导致 Swagger 不生效。此时需要手动配置静态资源路径[^3]。 - 确保所有依赖版本一致,避免因版本不兼容导致的问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值