Spring Boot 与Swagger REST api

Spring Boot 与Swagger结合搭建RESTful风格的API服务及API文档

  1. pom.xml 引入相关依赖
    <!-- 引入 spring-boot -swagger 并生成优美的API文档-->
       <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.2.2</version>
       </dependency>
       <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.2.2</version>
       </dependency>
    </dependencies>

  2. 创建Swagger2类
    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.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * ${DESCRIPTION}
     *
     * @author 温柔一刀
     * @create 2018-04-03 21:33
     **/
    @Configuration
    @EnableSwagger2
    public class Swagger2 {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.chf.springbootrestfulapi"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("API文档构建Restful Api")
                    .description("Spring Boot REST api")
                    .termsOfServiceUrl("https://projects.spring.io/spring-boot/")
                    .contact("温柔一刀")
                    .version("1.0")
                    .build();
        }
    }
  3. 创建RESTController
    import com.chf.springbootrestfulapi.entity.User;
    import com.chf.springbootrestfulapi.service.UserService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * ${DESCRIPTION}
     *
     * @author 温柔一刀
     * @create 2018-03-25 11:55
     **/
    @Api(value = "用户管理",description="user服务API")
    @RestController
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        private UserService userService;
        @ApiOperation("查询用户列表")
        @RequestMapping(value = "/",method = RequestMethod.GET)
        public List<User> getUserList(){
           return userService.getUserList();
         }
        @ApiOperation("查询单个用户")
        @RequestMapping(value = "/{id}",method = RequestMethod.GET)
         public  User getUser(@PathVariable Long id){
            return userService.get(id);
         }
        @ApiOperation("新增用户")
         @RequestMapping(value = "/",method = RequestMethod.POST)
        public String addUser(@ModelAttribute User user){
            userService.add(user);
            return "success";
    
        }
        @ApiOperation("修改用户")
        @RequestMapping(value = "/{id}",method = RequestMethod.POST)
        public String updateUser(@PathVariable Long id ,@ModelAttribute User user){
           User  oldUser=userService.get(id);
            oldUser.setAge(user.getAge());
            oldUser.setName(user.getName());
            userService.update(oldUser);
            return "success";
        }
        @ApiOperation("删除用户")
        @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
        public String deleteUser(@PathVariable Long id){
            userService.delete(id);
            return "success";
        }
    }
  4. 访问测试
    http://localhost:8080/api/swagger-ui.html
    
  5. 注解说明

    常用注解说明
    @ApiOperation和@ApiParam为添加的API相关注解,个参数说明如下:
    @ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码;
    @ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”


    在上面只展示了如何使用,这里将对上面添加的swagger注解进行说明,笔记使用时参考了swagger annotations Api 手册,接下来进行部分常用注解使用说明介绍。
    - @ApiIgnore 忽略注解标注的类或者方法,不添加到API文档中


    @ApiOperation 展示每个API基本信息


    value api名称
    notes 备注说明
    @ApiImplicitParam 用于规定接收参数类型、名称、是否必须等信息


    name 对应方法中接收参数名称
    value 备注说明
    required 是否必须 boolean
    paramType 参数类型 body、path、query、header、form中的一种
    body 使用@RequestBody接收数据 POST有效
    path 在url中配置{}的参数
    query 普通查询参数 例如 ?query=q ,jquery ajax中data设置的值也可以,例如 {query:”q”},springMVC中不需要添加注解接收
    header 使用@RequestHeader接收数据
    form 笔者未使用,请查看官方API文档
    dataType 数据类型,如果类型名称相同,请指定全路径,例如 dataType = “java.util.Date”,springfox会自动根据类型生成模型
    @ApiImplicitParams 包含多个@ApiImplicitParam


    @ApiModelProperty 对模型中属性添加说明,例如 上面的PageInfoBeen、BlogArticleBeen这两个类中使用,只能使用在类中。


    value 参数名称
    required 是否必须 boolean
    hidden 是否隐藏 boolean
    其他信息和上面同名属性作用相同,hidden属性对于集合不能隐藏,目前不知道原因
    @ApiParam 对单独某个参数进行说明,使用在类中或者controller方法中都可以。注解中的属性和上面列出的同名属性作用相同
    结合springfox使用查看,具体参照官网说明:https://swagger.io/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值