SpringMVC--Swagger2集成

已經有兩個月沒有更新啦,有不少東西都尚未整理出來,陸續會所有整理清晰再更新出來。html

相信全部的後臺開發人員都會寫接口文檔,並且也必須寫接口文檔,並且還必須條理清晰,負責就會被同事吐槽,並且接口變更,對應文檔也要變更,特別是入職沒有多久,尚未養成良好的文檔編寫習慣,極可能就會忘記編寫或更新接口文檔。因此爲了解決這個煩惱,Swagger2應運而生。java

1、什麼是 Swagger?git

Swagger是一款 RESTful 接口的文檔在線自動生成+功能測試的功能插件。Swagger是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。接口的文檔在線自動生成+測試,是否是很爽啊。接下來咱們就來看看它與SpringMVC的整合web

2、Swagger2 怎麼用?redis

一、添加包:spring

<!-- 2.8.0版本沒有測試成功,這裏採用2.7.0 -->
        <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>

二、編寫配置類:api

package com.gy.spring.mvc.common.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * TODO Swagger2配置類
 * Swagger2註解說明: https://blog.csdn.net/xiaojin21cen/article/details/78654652
 * @author geYang
 * @date 2018-04-16
 */
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
	
	@Bean
    public Docket customDocket() {
		return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select().apis(RequestHandlerSelectors.basePackage("com.gy.spring.mvc.controller"))
        .paths(PathSelectors.regex("/user/.*")) // "/.*" 爲全部接口
        .build();
        
    }
	
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        		.title("API接口文檔")
        		.description("API接口文檔描述")
        		.version("0.0.1")
        		.contact(new Contact("geYang", "https://my.oschina.net/u/3681868/home", "572119197@qq.com"))
//        		.termsOfServiceUrl("URL的服務條款")
//        		.license(null)
//        		.licenseUrl(null)
        		.build();
    }
	
}

三、Spring容器聲明(spring-mvc.xml):spring-mvc

<!-- 放行SwaggerUI的靜態文件 -->
	<mvc:default-servlet-handler />
	
	<!-- 聲明SwaggerConfig到容器 -->
	<bean class="com.gy.spring.mvc.common.interceptor.SwaggerConfig"/>

四、接口註解配置(Controller):緩存

package com.gy.spring.mvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gy.spring.mvc.entity.User;
import com.gy.spring.mvc.service.RedisService;
import com.gy.spring.mvc.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;



/**
 * TODO 用戶控制器
 * @author geYang
 * @date 2018-04-16
 */
@RestController
@RequestMapping("user")
@Api(description="用戶相關API")
public class UserController {
	@Autowired
	private RedisService redisService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * TODO 用戶列表
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:37
	 */
	@ApiOperation(value="用戶列表", notes="獲取全部用戶列表")
	@RequestMapping(value="list",method=RequestMethod.GET)
	public Object list() {
		String userList = redisService.get("user:list");
		if(userList==null) {
			userList = userService.selectList(null).toString();
			redisService.set("user:list", userList);
		}
		return userList;
	}
	
	/**
	 * TODO 用戶詳情
	 * @param id
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:37
	 */
	@ApiOperation(value="用戶詳情", notes="獲取用戶詳情")
	@ApiImplicitParams({
		@ApiImplicitParam(name="id",value="用戶ID",required=true,paramType="path",dataType="int"),
	})
	@RequestMapping(value="get/{id}",method=RequestMethod.GET)
	public Object get(@PathVariable("id") int id) {
		String userStr = redisService.get("user:"+id);
		if (userStr==null) {
			User user = userService.selectById(id);
			if(user!=null) {
				userStr = user.toString();
				redisService.set("user:"+id, userStr);
			}
		}
		return userStr;
	}
	
	/**
	 * TODO 用戶添加
	 * @param user
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:37
	 */
	@ApiOperation(value="用戶添加", notes="添加用戶信息")
	@RequestMapping(value="add",method=RequestMethod.POST)
	public Object add(User user) {
		return userService.insert(user);
	}
	
	/**
	 * TODO 用戶更新
	 * @param user
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:36
	 */
	@ApiOperation(value="用戶更新", notes="更新用戶信息")
	@RequestMapping(value="update",method=RequestMethod.PUT)
	public Object update(User user) {
		redisService.del("user:"+user.getId());
		return userService.updateById(user);
	}
	
	/**
	 * TODO 用戶刪除
	 * @param id
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:37
	 */
	@ApiOperation(value="用戶刪除", notes="刪除用戶詳情")
	@RequestMapping(value="del/{id}",method=RequestMethod.DELETE)
	public Object del(
			@ApiParam(name = "id", value = "用戶ID", required = true)
			@PathVariable("id") int id) {
		redisService.del("user:"+id);
		return userService.deleteById(id);
	}
	
	/**
	 * TODO 回滾測試
	 * @throws Exception
	 * @author geYang
	 * @date 2018-04-16 11:38
	 */
	@ApiOperation(value="回滾測試", notes="事務回滾測試")
	@RequestMapping(value="test",method=RequestMethod.GET)
	public void test() throws Exception {
		userService.test();
	}
	
	/**
	 * TODO 緩存測試
	 * @return
	 * @author geYang
	 * @date 2018-04-16 11:38
	 */
	@ApiOperation(value="緩存測試", notes="MyBatis二級緩存測試")
	@RequestMapping(value="testCache",method=RequestMethod.GET)
	public Object testCache(){
		userService.selectById(1);
		userService.selectById(1);
		return userService.selectById(1);
	}
}

到這裏就完成了簡單的集成配置,能夠進行測試了: http://localhost:8080/mvc/swagger-ui.htmlmvc

項目源碼: https://gitee.com/ge.yang/spring-demo/tree/master/spring-mvc

相關文章
相關標籤/搜索