spring mvc 整合Swagger2

swagger2可以自动生产接口文档,进行接口测试,方便前后交互,和接口测试。

1 引入依赖

   <!-- 整合swagger2 自动生成接口文档 -->
  <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger2</artifactId>
         <version>2.7.0</version>
     </dependency>
     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger-ui</artifactId>
         <version>2.7.0</version>
     </dependency>

2 配置文件

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket accessToken() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("api")// 定义组
                .select() // 选择那些路径和 api 会生成 document
                .apis(RequestHandlerSelectors.basePackage("com.cc.controller")) // 拦截的包路径,注意大小写
//                .paths(PathSelectors.regex("/*/.*"))// 拦截的接口路径
                .paths(PathSelectors.any())
                .build() // 创建
                .apiInfo(apiInfo()); // 配置说明
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()//
                .title("Spring mvc Demo API")// 标题
                .description("spring mvc Demo")// 描述
//                .termsOfServiceUrl("http:/localhost:8080")//
//                .contact(new Contact("cc", "http:/localhost:8080", "cc@qq.com"))// 联系
                .version("1.0")// 版本
                .build();
    }
}

3 controller

@Controller
@Api("json demo")
public class JsonController {

    @PostMapping("kv2Json")// 需要指定post或者get请求,不然swagger会生成七种请求【delete\get\head\options\patch\post\put】
    @ResponseBody
    @ApiOperation("键值对转化为json数据")
    @ApiImplicitParams({@ApiImplicitParam(name="id",value = "用户id",dataType = "string"),
        @ApiImplicitParam(name="name",value = "用户名",dataType = "String")})
    public User kv2Json(User user){
        return user;
    }

    @PostMapping("json2Json")
    @ResponseBody
    @ApiOperation(value = "请求和响应均为json数据",notes = "sssssssssssss")
    @ApiImplicitParam(name="user",value = "用户信息",dataType = "json")
    public User json2Json(@RequestBody User user){
        return user;
    }
}

4 获取接口文档

访问 http://localhost:8080/swagger-ui.html 可以看到接口文档信息
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值