RESTful API的灵魂伴侣——Swagger

开篇总是要写一些概括性的东西!

 

    Swagger 是一个RESTful接口的文档的实时生成与测试工具。没接触过类似工具的你可能对这句话没什么概念,不要急,我来慢慢解释。

    使用REST的原因之一就是方便前后端分离开发,后端开发者写后端的逻辑,前端开发者写前端的逻辑,然后大家约定好一个API的风格,使用HTTP的get、post、put、delete来对应资源的CURD。避免了这种情况的发生:前端开发者拿着后端提供的厚厚的API文档边查阅边愤愤地开发,每个业务逻辑对应一个接口规范,混乱不堪。然后某一天后端改了逻辑,删掉了几个接口又增加了几个接口,前端又要大范围地改代码,然后前后端就打起来了。

    为了避免打架,规范了API的设计,使用了较为轻便的RESTful风格。而Swagger起到一个锦上添花的作用,它使得前后端的协同变得更加效率。后端开发者在定义好接口后,Swagger会自动生成并更新文档,文档中会详细记录接口的使用方法,需要传入哪些参数,又会返回什么样的结果,即节约了写文档的时间,又提高了文档的同步速度,提高了开发效率。另外Swagger不止这些功能,它还有一个强大的功能,就是在文档中直接对接口进行测试,我们可以使用Swagger模拟用户的真实操作,向后台发一个请求来验证接口是否满足需求。说了这么多,可能你还是不太明白,那我直接贴张图片吧,下图就是Swagger生成的文档:

 

 

 

 

 

    算了,不截图了,直接给个链接吧:http://petstore.swagger.io/?_ga=2.151670393.1145939008.1514200525-1067691787.1514200525

    这是官方提供一个demo文档,可以简单操作一下,聪明的你应该豁然开朗了吧!

 

    好了,Swagger介绍完了,相信大家已经认识他了吧。下面我将介绍如何在spring mvc项目中嵌入Swagger:

    本文使用 springfox-swagger实现Swagger的集成。很简单,仅仅几步就可搞定!

步骤↓:

  1. 引入jar包,此处笔者使用maven,直接引入依赖:
    		<!-- swagger RestfulAPI 文档工具 -->
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger2</artifactId>
    			<version>${springfox.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger-ui</artifactId>
    			<version>${springfox.version}</version>
    		</dependency>
     此处使用的版本是springfox.version=2.6.1
  2. 重写一下Swagger的配置类并声明成bean:
    package com.ds.core.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @EnableWebMvc
    @EnableSwagger2
    @ComponentScan("com.ds.literary.controller")//配置Swagger要扫描的包
    @Configuration
    public class SwaggerConfig extends WebMvcConfigurationSupport {
    
    	@Bean
    	public Docket docket() {
    		return new Docket(DocumentationType.SWAGGER_2)
    				.apiInfo(apiInfo())
    				.groupName("Du")
    				.select()
    //				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
    //				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
    				.paths(PathSelectors.any())
    				.build();
    	}
    
    //	@Bean
    //	public Docket xxx() {
    //		return new Docket(DocumentationType.SWAGGER_2)
    //				.apiInfo(apiInfo())
    //				.groupName("xxx")
    //				.select()
    //				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
    //				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
    //				.paths(PathSelectors.ant("/xxx/**"))
    //				.build();
    //	}
    
    	private ApiInfo apiInfo() {
    		return new ApiInfoBuilder()
    				.title("Ds")
    				.contact(new Contact("Du", "", "[email protected]"))
    				.version("0.0.1")
    				.build();
    	}
    }
     
  3. 在写controller的时候加入一些annotation就好了:
    @RestController
    @RequestMapping("/blog")
    @Api(value = "管理用户发表的博客,文章,日志接口", description = "管理用户发表的博客,文章,日志接口")
    public class BlogController extends BaseController<Blog>{
    	public String getService() {
    		return "blogService";
    	}
    
    	@PutMapping
    	@ApiOperation(value = "修改用户发表的博客,文章,日志", produces = MediaType.APPLICATION_JSON_VALUE)
    	public Object update(HttpServletRequest request, @RequestBody Blog param) {
                    ModelMap modelMap = new ModelMap();
                    long authorId=getCurrUser();
                    param.setAuthorId(authorId);
    		return super.update(modelMap, param);
    	}
    
    	@DeleteMapping
    	@ApiOperation(value = "删除用户发表的博客,文章,日志", produces = MediaType.APPLICATION_JSON_VALUE)
    	public Object delete(HttpServletRequest request, @RequestBody Blog param) {
                    ModelMap modelMap = new ModelMap();
    		return super.delete(modelMap, param);
    	}
    }
     
  4. 在spring中配置一个资源重定向:
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
     
  5. 启动项目,打开默认文档界面http://localhost:8080/ds-sys-web/swagger-ui.html,这个路径根据你的实际情况修改。如果你觉得这个界面丑,是可以自己定制的,具体方法本篇就不介绍了。

下面是成功后的截图:

 

搞定!酷

猜你喜欢

转载自dushen.iteye.com/blog/2405714
今日推荐