Swagger的使用

Swagger的使用

pom.xml中添加依赖

 <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>

添加配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swagger_demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .version("1.0")
                .build();
    }

}

注解添加文档内容

  1. @Api:给类添加说明
  2. @ApiOperation:给api方法添加说明
  3. @ApiImplicitParam : 给api方法参数添加说明。
  4. @ApiImplicitParams:包含多个 @ApiImplicitParam
  5. @ApiResponses:用于表示一组响应
  6. @ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
  7. @ApiResponse:组装返回参数说明
  8. @ApiResponses:包含多个 @ApiResponse

案列:

@Controller
@Api(value = "测试类控制器")
public class IndexController {
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试方法1")
    public String index() {
        return "hi,how are you?";
    }
    @RequestMapping(value = "/index2",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "测试方法2")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query",name = "id",value = "用户ID",dataType = "int",required = true),
            @ApiImplicitParam(paramType = "query",name = "name",value = "用户名",dataType = "String",required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 404,message = "请求参数缺少!")
    })
    public String index2(Integer id,String name) {
        return "hi,your post params id="+id+",name="+name;
    }
}

http://localhost:8081/swagger-ui.html
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值