美文网首页技匠志Spring Boot&Spring CloudIT技术篇
使用Spring Boot&Swagger快速构建RES

使用Spring Boot&Swagger快速构建RES

作者: 简单的土豆 | 来源:发表于2016-10-13 14:38 被阅读8791次

通常我们要构建API 服务,自然少不了文档,但由于API与文档的分离使得我们每次对API进行的更改都需要去同步文档,稍有纰漏难免就会出现调用的异常,而编写、同步文档通常是比较繁琐无趣的事。现在得益于Spring BootSwagger,我们不但可以极速的搭建REST、RESTful风格的API服务并且还可以生成优美、强大的在线或离线API文档。

  • 引入Maven依赖
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>
  • 创建Application主类
package example;//注意包结构
@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
  • 创建Swagger配置类
package example.config;//注意包结构
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("example.web.controller"))//要扫描的API(Controller)基础包
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo buildApiInf() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2 UI构建API文档")
                .contact("土豆")
                .version("1.0")
                .build();
    }
}
  • 创建RestController 构建一个简单计算服务API
package example.web.controller;//注意包结构
@Api(value = "计算服务",description="简单的计算服务,提供加减乘除运算API")
@RestController
@RequestMapping("/compute")
public class ComputeController {
      @ApiOperation("加法运算")
      @PostMapping("/add")
      public Double add(@RequestParam Double a,  @RequestParam Double b) {
         return a + b;
      }
   
      @ApiOperation("减法运算")
      @PostMapping("/sub")
      public Double sub(@RequestParam Double a,  @RequestParam Double b) {
          return a - b;
      }

      @ApiOperation("乘法运算")
      @PostMapping("/mul")
      public Double mul(@RequestParam Double a,  @RequestParam Double b) {
          return a * b;
      }

      @ApiOperation("除法运算")
      @PostMapping("/div")
      public Double div(@ApiParam("被除数")@RequestParam Double a, @ApiParam("除数")@RequestParam   Double b) {
          return a / b;
      }
}

@Api注解用来表述该服务的信息,如果不使用则显示类名称.
@ApiOperation注解用于表述接口信息
@ApiParam注解用于描述接口的参数

通过上面几步我们已经成功构建了一个具备加减乘除的计算服务API,并且已经拥有一份不错的在线文档了,现在我们来启动它,执行mvn spring-boot:run,或直接运行Application.main()

启动成功后,访问http://localhost:8080/swagger-ui.html,便可以看到我们刚才构建的计算服务的API文档了。

swagger-ui
Swagger UI不仅仅是文档,还提供了在线API调试的功能,我们可以调试下我们的除法运算API。
swagger-ui
点击Try it out!后可以看到我们成功的调用了除法运算API并获得了正确的响应。
swagger-ui
  • 创建RESTful 风格的API及文档

下面我们以用户的增删改查服务为例

1.创建Model

package example.model;//注意包结构
public class User {

    private Long id;
    private String username;
    private Integer age;
    
    //省略getter、setter方法
    
}

2.创建RestController

package example.web.controller;//注意包结构
@RestController
@RequestMapping("/user")
@Api(value = "用户服务",description = "提供RESTful风格API的用户的增删改查服务")
public class UserController {
    //模拟DAO层
    private final Map<Long, User> repository = new HashMap<Long, User>();

    @PostMapping
    @ApiOperation("添加用户")
    public Boolean add(@RequestBody User user) {
        repository.put(user.getId(), user);
        return true;
    }

    @DeleteMapping("/{id}")
    @ApiOperation("通过ID删除用户")
    public Boolean delete(@PathVariable Long id) {
        repository.remove(id);
        return true;
    }

    @PutMapping
    @ApiOperation("更新用户")
    public Boolean update(@RequestBody User user) {
        repository.put(user.getId(), user);
        return true;
    }

    @GetMapping("/{id}")
    @ApiOperation("通过ID查询用户")
    public User findById(@PathVariable Long id) {
        return repository.get(id);
    }
}

这里说点题外话,@GetMapping,@PostMapping,@PutMapping,@DeleteMapping 等注解是Spring MVC 4.3X版本添加的新注解,它们是对@RequestMapping注解的简化封装。

好了,我们重新启动下Application,再次访问http://localhost:8080/swagger-ui.html,用户服务的RESTful API文档也已生成。

swagger-ui

我们来尝试调用添加用户API增加一位用户

swagger-ui

成功后,我们调用查询API,来进行查询看时候可以返回正确的JSON数据。

swagger-ui
  • 为Model(JSON)添加注释

为了使API的调用者能够清晰的知道请求和响应的Model中各字段的具体含义,我们需要对其添加一些简单的注释,而Swagger也为我们提供了相应的注解比如@ApiModel、@ApiModelProperty来帮助我们解释我们的Model,下面就是最简单的使用例子,详细用法及更多相关注解点我查看~

@ApiModel("User(用户模型)")
public class User {
     @ApiModelProperty("ID")
     private Long id;
     @ApiModelProperty("用户名")
     private String username;
     @ApiModelProperty("年龄")
     private Integer age;

     //省略getter、setter方法
}
swagger-ui

这一切是不是很简单?从开发API到构建高逼格的API文档完全可以用极速来形容。当然,本文也只是展现了Spring Boot + Swagger的冰山一角,要了解更多细节那就快去翻阅官方文档吧~

本示例完整代码的GIT地址点击我~
Swagger-Core文档点击我~
SpringFox文档点击我~
Spring Boot 文档点击我~
还不错的Spring Boot系列教程点击我~

相关文章

网友评论

  • _小田:学习了 零基础用springboot 写 api还是蛮累的
  • wdom:学习了,按照讲解生成了API文档,很好用哦,不过修改了很多配置和代码。要是脱离代码就能生成API文档就完美了,有个小工具完全不必修改代码就能生成API文档,
    Wisdom RESTClient
    https://github.com/Wisdom-Projects/rest-client

    谢谢作者的分享,很喜欢!
  • 1e4259d35aae:我返回的是map类型,怎么在写map里面的字段代表的意思
  • 天草二十六_简村人:不需要它自身的HTML和JS了吧?
  • andycheng:赞,暂时还没有用spring boot,有没有非spring boot,纯spring mvc的swagger使用配置的文章?
  • hythzx:已经在项目中实际使用一段时间了,做前后端分离,和Angular的resource搭配很不错
  • b410c77ceaef:对于@RepositoryRestResource自动生成的api,怎么添加
  • 308a72355c56:谢谢谢谢~~:smile:
  • leeyaf:誓死不入Spring的坑! :bangbang:
  • 流花飘原:感谢作者!!!
    简单的土豆:@流花飘原 客气,很高兴能帮到你。
  • scorpionfeng:不错,一直想弄一个这个
  • 慧明小和尚下山去化斋:最近正想在做rest后台
  • 流花飘原:如何写json包的解释
    流花飘原:@简单的土豆 十分感谢!
    简单的土豆:@流花飘原 由于评论回复不太方便解答,我更新了本文,你可以看下文章下方新增的篇幅,并且示例代码也进行了更新。
  • da8dd5b1884d:如何自定义swagger的header
    简单的土豆:@PleasecallmeDem http://springfox.github.io/springfox/docs/current/#dependencies
    2.1.3你看下,很简单,本文就不做演示了
    da8dd5b1884d:@简单的土豆 Authorization
    简单的土豆:@PleasecallmeDem 什么header?
  • Rick____:Swagger 有一点不好,就是没法写json 的解释
    聆听者JYZ:如果在返回数据外层在包一层结果集,我们注解的model就不能显示json解释了,有办法处理下吗
    Rick____:@简单的土豆 好
    简单的土豆:@Zeroff 可以的,由于评论回复不太方便解答,我更新了本文,你可以看下文章下方新增的篇幅,并且示例代码也进行了更新。

本文标题:使用Spring Boot&Swagger快速构建RES

本文链接:https://www.haomeiwen.com/subject/majwyttx.html