springBoot 集成swagger API 指南和demo案例

本文介绍如何在SpringBoot项目中集成Swagger,实现API文档自动生成及在线测试功能。包括依赖配置、自动注入配置及注解使用等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springBoot 集成swagger API 指南和demo

为什么需要API的文档

随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、先后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。

前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要,swagger就是一款让你更好的书写API文档的框架。

使用指南

1.依赖jar包

 <!-- API Swagger begin -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>net.minidev</groupId>
            <artifactId>json-smart</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20171018</version>
        </dependency>
        <!-- API Swagger end -->

2.swagger 的自动注入配置

源码

/**
 * com.lew.jlight.web.config.SwaggerConfig.java
 * Copyright 2017 Lifangyu, Inc. All rights reserved.
 * GomeGJ PROPRIETARY/CONFIDENTIAL.Use is subject to license terms.
 */
package com.hshc.as.configs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;

/**
 * Desc:swagger api 的配置
 * <p>
 * 访问:http://ip:port/swagger-ui.html
 * [localhsot:8081/swagger-ui.html 可能有登录拦截,需要先登录系统后在访问该地址]
 * </p>
 * <p>
 * Created by lifangyu on 2017/4/19.
 */
@Conditional(SwaggerCondition.class)
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * /api.* [访问的路径匹配,如:SwaggerApiController.java @RequestMapping("/api/v1") 符合该路径匹配]
     *
     * @return
     */
    @Bean
    public Docket userApi() {

        // 添加多个header或参数
        /*ParameterBuilder parameterBuilder1 = new ParameterBuilder();
        parameterBuilder1.name("clientCode").description("访问的系统clientCode").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        ParameterBuilder parameterBuilder2 = new ParameterBuilder();
        parameterBuilder2.name("timestamp").description("请求api的当前时间(long[yyyy-MM-dd HH:hh:ss SSS])").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        ParameterBuilder parameterBuilder3 = new ParameterBuilder();
        parameterBuilder3.name("encrypt-key").description("请求api的认证密文").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        List<Parameter> parameterList = new ArrayList<Parameter>();
        parameterList.add(parameterBuilder1.build());
        parameterList.add(parameterBuilder2.build());
        parameterList.add(parameterBuilder3.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false).globalOperationParameters(parameterList)
                .select()
                .paths(PathSelectors.regex("/api.*"))
                .build();*/

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()// 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.any()) // 对所有@Api注解进行监控
//                .paths(PathSelectors.any()) // 对所有路径进行监控[指定匹配路径监控(PathSelectors.regex("/api.*"))]
                .build();
    }

    /**
     * 确保以下配置的信息可用,否则不能访问
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("****-**系统接口文档")
                .description("**-server系统接口文档")
                .license("Apache license")
                .version("2.0")
                .build();
    }
}

为了防止在生产环境恶意攻击api接口,建议关闭生产环境通过swagger api对接口的访问,源码:

/**
 * com.lew.jlight.web.config.SwaggerCondition.java
 * Copyright 2017 Lifangyu, Inc. All rights reserved.
 * GomeGJ PROPRIETARY/CONFIDENTIAL.Use is subject to license terms.
 */
package com.hshc.as.configs;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * Desc:指定swagger api 生成的条件:非生产环境生成
 * <p>
 * Created by lifangyu on 2017/4/19.
 */
public class SwaggerCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return !"prod".equals(context.getEnvironment().getProperty("spring.profiles.active"));
    }

}

3.swagger-ui API文档生成使用

(1) 在写好的api controller 上添加注解@Api(value = “demo controller”, protocols = “json”)

说明:指定该controller使用swagger生成api文档;

(2)在方法上添加注解
@ApiOperation(value = “车务系统-gps信息同步”, httpMethod = “POST”, notes = “from gps系统 to 系统”)

说明:该方法使用swagger 生成api接口文档,提供测试服务;

demo


@RestController
@Slf4j
@Api
@RequestMapping("/as/api/v1")
public class GpsApi {
 ...

    @PostMapping("syncGpsInfo")
    @ApiOperation(value = "车务系统-gps信息同步", httpMethod = "POST", notes = "from gps系统 to 车务系统")
    @RequestLogger("车务系统-gps信息同步[/as/api/v1/syncGpsInfo]")
    @ResponseBody
    public ResponseVo syncGspInfo(@RequestBody RequestVo<GpsSyncRequestVo> requestVo) {

     ......
     }

 ...


}

swagger-ui api文档 的访问

启动应用,在浏览器输入:http://ip:port/swagger-ui.html

类似下图:
swagge

可以提供接口api文档的说明和api的测试!

附:swagger 生成API文档的注释


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

@ApiOperation:注解来给API增加方法说明。

@ApiImplicitParams : 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

    1.code:数字,例如400

    2.message:信息,例如"请求参数没填好"

    3.response:抛出异常的类   

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

@ApiModelProperty:描述一个model的属性

注意:@ApiImplicitParam的参数说明:
paramType:指定参数放在哪个地方
header:请求参数放置于Request Header,使用@RequestHeader获取
query:请求参数放置于请求地址,使用@RequestParam获取
path:(用于restful接口)-->请求参数的获取:@PathVariable
body:(不常用)
form(不常用)
name:参数名 
dataType:参数类型
required:参数是否必须传 true | false
value:说明参数的意思 
defaultValue:参数的默认值

springMVC 项目集成swagger下次详解!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值