springboot如何集成swagger,swagger如何为所有API添加token参数,swagger常用注解,简介明了,举例说明

本文详细介绍了如何在SpringBoot项目中集成Swagger,包括添加依赖、配置Swagger2、控制器注解应用、全局参数设置以及常见注解的使用。通过步骤指导,帮助开发者快速生成API文档并实现参数验证。
摘要由CSDN通过智能技术生成

springboot集成swagger

如何使用swagger生成Web API

1.在pom文件中添加如下依赖

<!-- swagger2 依赖配置-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

2.创建swagger配置类

package com.yangjunbo.helloword.properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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;

@Configuration
@EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {
    //指定需要扫描的包路径
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //编辑网站信息,如网站的标题、网站的描述、使用的协议等。
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("Spring Boot相关文章请关注:https://www.cnblogs.com/zhangweizhong")
                .termsOfServiceUrl("https://www.cnblogs.com/zhangweizhong")
                .contact("架构师精进")
                .version("1.0")
                .build();
    }
    /**
     *  swagger增加url映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

3.在controller类上添加注解说明

package com.yangjunbo.helloword.controller;

import com.yangjunbo.helloword.common.JSONResult;
import com.yangjunbo.helloword.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Api(tags={"用户接口"})
@RestController
public class UserController {

    @ApiOperation(value = "创建用户",notes="根据user对象创建用户")
    @PostMapping(value = "user")
    public JSONResult save(@RequestBody User user){
        System.out.println("用户创建成功"+user.getName());
        return JSONResult.ok(201,"用户创建成功");

    }

    @ApiOperation(value = "更新用户信息",notes="根据ID来指定更新对象,并根据传过来的user信息来更新用户信息")
    @PutMapping(value = "user")
    public JSONResult update(@RequestBody User user) {
        System.out.println("用户修改成功:"+user.getName());
        return JSONResult.ok(203,"用户修改成功");
    }

    @ApiOperation(value = "删除用户信息",notes="根据URL中的ID指定删除对象")
    @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
    @DeleteMapping("user/{userId}")
    public JSONResult delete(@PathVariable String userId) {
        System.out.println("用户删除成功:"+userId);
        return JSONResult.ok(204,"用户删除成功");
    }

    @ApiOperation(value = "获取用户信息",notes="根据URL中的ID获取指定对象")
    @ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
    @GetMapping("user/{userId}")
    public JSONResult queryUserById(@PathVariable String userId) {
        User user =new User();
        user.setName("weiz");
        user.setAge(20);
        System.out.println("获取用户成功:"+userId);
        return JSONResult.ok(200,"获取用户成功",user);
    }
}

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

在这里插入图片描述

5.使用 try it out 测试接口

在这里插入图片描述在这里插入图片描述

6.为所有API添加token参数

修改上面的swagger配置类中的creatRestApi方法,如下

		@Bean
    public Docket createRestApi() {

        //添加请求参数,这里把token作为请求头参数传入后端
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameterList = new ArrayList<Parameter>();
        parameterBuilder.name("token").description("token令牌").modelRef(new ModelRef("String")).parameterType("header")
                .required(false).build();
        parameterList.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameterList);
    }

重新启动项目,再次访问swagger主页,发现API已经支持添加token参数了,swagger会自动把token参数放到请求头中
在这里插入图片描述

7.swagger常用注解

在这里插入图片描述

参考书籍:springboot从入门到实战-章为忠编著

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值