Spring结合Swagger实现API管理

来源:互联网 发布:常德跑胡子源码 编辑:程序博客网 时间:2024/06/01 20:21

前言


        在日常的开发过程中,再进行前后端协作的过程中,遇到的API管理方式简直是多不胜数啊!而且大家还都是各有特点,比如说word书写的文档,markdown书写的,什么,你说你用记事本写,这个倒还真的是莫有见过。总的来说就是大家对于API文档压根很不重视。还有一点,我记得我当初在做重构的时候,那时候已经是2016年了,但是文档相关的接口的文档还停留在2014年好吗?主要的问题是那个时候接口还是有调用量的好吗?而且量还不少呢!接口的文档更新的不及时也是相当之普遍啊!当然,如上所述都是我们在日常的开发中遇到的一些问题,而我们今天,就是想要借助Swagger来优化API文档的管理。


Spring-Fox使用

        说句实在话,网上这样的教程简直是多不胜数。然而我看了好多类似的教程之后,最深切的感受是,不知所云。
        这样说的原因是看了那些个教程还是无法将其整合到自己的项目中去。好吧,看来阿福只能亲自出马了。
        具体的来说,最权威的文档在哪里?当然是官网了。实际上在官网上获取的资料也更加权威。这里的话,我直接打开了Swagger的官网,虽然并没有发现任何的相关文档,但是在Swagger-Editor的OnLine版本里面发现了一个有趣的功能,简而言之就是其可以为你生成相关的语言的服务端的例子。这个功能简直好用的不行不行的。
        那么,这个好用的功能在哪里呢?首先打开http://editor2.swagger.io/#!/,这是Swagger-Editor的在线版本,当然你也可以安装本地版本,然而本地版本是没有类似的功能的。如果你无法科学上网的话,阿福也无能为力。接下来,看下面的图片就明白了!选取你所使用的语言就ok了。


32


        下面就是生成的项目的简单截图。


1


        我们可以看到这里的话Swagger自动生成的项目中采取了目前最流行的微服务架构-SpringBoot。当然,这让我们的配置变得越加简单了。现在我们就来一起看看这里面的门道!
        首先,Swagger2SpringBoot是整个项目的启动中心。其主要代码如下:

package io.swagger;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.ExitCodeGenerator;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;import springfox.documentation.swagger2.annotations.EnableSwagger2;@SpringBootApplication@EnableSwagger2@ComponentScan(basePackages = "io.swagger")public class Swagger2SpringBoot implements CommandLineRunner {    @Override    public void run(String... arg0) throws Exception {        if (arg0.length > 0 && arg0[0].equals("exitcode")) {            throw new ExitException();        }    }    public static void main(String[] args) throws Exception {        new SpringApplication(Swagger2SpringBoot.class).run(args);    }    class ExitException extends RuntimeException implements ExitCodeGenerator {        private static final long serialVersionUID = 1L;        @Override        public int getExitCode() {            return 10;        }    }}

        这里的话实际上是会去扫描相关的注解。那么,我们去看看配置都需要什么?

package io.swagger.configuration;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;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;@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-04-05T01:24:56.281Z")@Configurationpublic class SwaggerDocumentationConfig {    ApiInfo apiInfo() {        return new ApiInfoBuilder()            .title("Uber API")            .description("Move your app forward with the Uber API")            .license("")            .licenseUrl("http://unlicense.org")            .termsOfServiceUrl("")            .version("1.0.0")            .contact(new Contact("","", ""))            .build();    }    @Bean    public Docket customImplementation(){        return new Docket(DocumentationType.SWAGGER_2)                .select()                    .apis(RequestHandlerSelectors.basePackage("io.swagger.api"))                    .build()                .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)                .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)                .apiInfo(apiInfo());    }}

        上面的话无非是配置了简单的开发者信息,当然,我们关注的是下面的那个方法,它配置了我们的API的存放位置。这是非常重要的。接下来,我们去看看如何配置一个简单的接口。

package io.swagger.api;import io.swagger.model.Error;import io.swagger.model.Profile;import io.swagger.annotations.*;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PathVariable;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.RequestPart;import org.springframework.web.multipart.MultipartFile;import java.util.List;import javax.validation.constraints.*;@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-04-05T01:24:56.281Z")@Api(value = "me", description = "the me API")public interface MeApi {    @ApiOperation(value = "User Profile", notes = "The User Profile endpoint returns information about the Uber user that has authorized with the application.", response = Profile.class, tags={ "User", })    @ApiResponses(value = {         @ApiResponse(code = 200, message = "Profile information for a user", response = Profile.class),        @ApiResponse(code = 200, message = "Unexpected error", response = Profile.class) })    @RequestMapping(value = "/me",        produces = { "application/JSON" },         method = RequestMethod.GET)    ResponseEntity<Profile> meGet();}

        上面的配置就是一个简单的配置。我们可以看到其可以通过在代码上加注解的方式实现API的生成。最后,让我们一起来看看效果。启动项目访问相关的路径,http://localhost:8080/v1/api-docs即可看到生成的json接口数据。


2


        访问http://localhost:8080/v1/swagger-ui.html即可看到完整的API呈现。如下图所示:


这里写图片描述


总结

        上面我们简单的讲了下如何结合Swagger管理java的API,也看到了果然官方文档还是比较腻害的。那还等啥,赶紧用起来吧!
        然而如果你没有一个很好的翻墙的梯子的话,做起来还是比较麻烦的。那么,我把生成的项目实际上已经上传到我的GitHub上,ok,下面是地址,https://github.com/wangmeng1314/java-project。
        希望大家在API管理这件事上有啥好的意见可以多多提出偶!感谢大家看完这篇文章!

1 0