springboot与Swagger整合

swagger作用

1.在线接口工具

2.还可导出json格式,导入yapi,最后自动生成接口文档

http://127.0.0.1:8023/v2/api-docs

依赖架包

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

依赖SwaggerConfiguration类

依赖注解@Configuration,目的spring扫描

注解@EnableSwagger2,目的标志可用的swagger2文件

RequestHandlerSelectors.basePackage(“com.lance.learn.springbootswagger.controller”)包的地址根据当前SwaggerConfiguration类的路径而定;

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

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     * @return
     */
    @Bean
    public Docket createRestfulApi(){
        return new Docket(DocumentationType.SWAGGER_2)
        		.apiInfo(apiInfo())
                .select()
.apis(RequestHandlerSelectors.basePackage("com.lance.learn.springbootswagger.controller"))  //暴露接口地址的包路径
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API")
                //创建人
                .contact(new Contact("testfan", "http://ask.testfan.cn", "917484312@qq.com"))
                //版本号
                .version("2.0")
                //描述
                .description("API 描述")
                .build();
    }

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VPQhKpEt-1584257246449)(C:\Users\wys\AppData\Roaming\Typora\typora-user-images\image-20200315144610933.png)]

Swagger使用的注解及其说明

@Api(tags = “swagger例子”) //用在类上,说明该类的作用

@ApiOperation(value="") //给API增加方法说明

@ApiImplicitParam(paramType=“query”) //参数说明

@ApiImplicitParams //一组参数说明

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uhOjPtK5-1584257246450)(C:\Users\wys\AppData\Roaming\Typora\typora-user-images\image-20200315145559378.png)]

测试一下:

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 一个用来测试swagger注解的控制器
 * 注意@ApiImplicitParam的使用会影响程序运行,如果使用不当可能造成控制器收不到消息
 * 
 */
@Controller
@RequestMapping("/say")
@Api(tags = "swagger例子")
public class SayController {
    
   @ResponseBody
   @RequestMapping(value ="/getUserName",method = RequestMethod.GET)
   @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回")
   @ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")
   public String getUserName(@RequestParam Integer userNumber){
        if(userNumber == 1){
            return "张三丰";
        }
        else if(userNumber == 2){
            return "慕容复";
        }
        else{
            return "未知";
        }
    }
    
    @ResponseBody
    @RequestMapping(value="/updatePassword", method= RequestMethod.POST)
    @ApiOperation(value="修改用户密码", notes="根据用户id修改密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    public String updatePassword(Integer userId,  String password,  String newPassword){
      if(userId <= 0 || userId > 2){
          return "未知的用户";
      }
      if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
          return "密码不能为空";
      }
      if(password.equals(newPassword)){
          return "新旧密码不能相同";
      }
      return "密码修改成功!";
    }
    
    
    @ResponseBody
    @ApiOperation(value="获取用户详细信息", notes="根据url中的id来获取用户详细信息")
    @ApiImplicitParam(paramType="path",name = "id", value = "用户ID", required = true, dataType = "Integer")
    @GetMapping(value="/test/{id}")
    public String getUser(@PathVariable Integer id) {
        return ""+id;
    }
    
    @ResponseBody
    @ApiOperation(value="获取用户详细信息及token", notes="根据url中的id来获取用户详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="path", name = "id", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="header", name = "token", value = "token信息", required = true, dataType = "String"),
    })
    @GetMapping(value="/test-header/{id}")
    public String getUser(@PathVariable Integer id, @RequestHeader(value="token") String userAgent) {
        return "id "+id+" token "+userAgent;
    }
    
    @ResponseBody
    @ApiOperation("json测试更改用户信息")
    @ApiImplicitParam(paramType="body", name = "json", value = "用户ID", required = true, dataType = "String")
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody String json){
       return json;
    }
}

访问路径: http://localhost:8023/swagger-ui.html

在这里插入图片描述

@ApiImplicitParam参加类型具体介绍

query类型,一个参数

@RequestParam

   @ResponseBody
   @RequestMapping(value ="/getUserName",method = RequestMethod.GET)
   @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回")
   @ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")
   public String getUserName(@RequestParam Integer userNumber){
        if(userNumber == 1){
            return "张三丰";
        }
        else if(userNumber == 2){
            return "慕容复";
        }
        else{
            return "未知";
        }
    }

在这里插入图片描述

query类型,多个参数
	@ResponseBody
    @RequestMapping(value="/updatePassword", method= RequestMethod.POST)
    @ApiOperation(value="修改用户密码", notes="根据用户id修改密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    public String updatePassword(Integer userId,  String password,  String newPassword){
      if(userId <= 0 || userId > 2){
          return "未知的用户";
      }
      if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
          return "密码不能为空";
      }
      if(password.equals(newPassword)){
          return "新旧密码不能相同";
      }
      return "密码修改成功!";
    }

在这里插入图片描述

path类型

@PathVariable

	@ResponseBody
    @ApiOperation(value="获取用户详细信息", notes="根据url中的id来获取用户详细信息")
    @ApiImplicitParam(paramType="path",name = "id", value = "用户ID", required = true, dataType = "Integer")
    @GetMapping(value="/test/{id}")
    public String getUser(@PathVariable Integer id) {
        return ""+id;
    }

在这里插入图片描述

header和path类型组合

@PathVariable

@RequestHeader

	@ResponseBody
    @ApiOperation(value="获取用户详细信息及token", notes="根据url中的id来获取用户详细信息")
    @ApiImplicitParams({
    @ApiImplicitParam(paramType="path", name = "id", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="header", name = "token", value = "token信息", required = true, dataType = "String"),
    })
    @GetMapping(value="/test-header/{id}")
    public String getUser(@PathVariable Integer id, @RequestHeader(value="token") String userAgent) {
        return "id "+id+" token "+userAgent;
    }

在这里插入图片描述

body类型

@RequestBody

	@ResponseBody
    @ApiOperation("json测试更改用户信息")
    @ApiImplicitParam(paramType="body", name = "json", value = "用户ID", required = true, dataType = "String")
    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody String json){
       return json;
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值