Swagger2解决通用返回结果是泛型的问题:swagger2.9.2+ swagger-bootstrap-ui-1.8.5

Swagger2解决通用返回结果是泛型的问题:swagger2.9.2+ swagger-bootstrap-ui-1.8.5 

依赖关系

<!-- Swagger2 -->
		    <dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${springfox-swagger2}</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${springfox-swagger2}</version>
		</dependency>
		<dependency>
			<groupId>com.google.collections</groupId>
			<artifactId>google-collections</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>swagger-bootstrap-ui</artifactId>
			<version>${swagger-bootstrap-ui}</version>
		</dependency>

通用的返回结果类:主要是要解决data属性的参照关系

@ApiModel(description = "通用响应返回对象")
public class JsonResult<T> extends BaseResult {
	protected static Logger logger = LoggerFactory.getLogger(JsonResult.class);
	/**
	 * 返回结果代码
	 */
	@ApiModelProperty(value = "结果代码", position = 0)
	private int code;
	/**
	 * 返回结果类型
	 */
	@ApiModelProperty(value = "结果类型", position = 1)
	private String type;
	/**
	 * 具体的错误信息
	 */
	@ApiModelProperty(value = "错误信息", position = 2)
	private String message;
	/**
	 * Exception类
	 */
	@ApiModelProperty(value = "异常类", position = 3)
	private String exception;
	/**
	 * 返回结果数据
	 */
	@ApiModelProperty(value = "结果数据", position = 4 )
	private T data;

	/**
	 * 是否成功,0表示成功,其他都是失败
	 */
	@ApiModelProperty(value = "是否成功", position = 5, example = "true")
	private boolean success = true;

	/**
	 * 具体的异常类 <br>
	 * JSON序列化时,将该字段忽略
	 */
	@JSONField(serialize = false)
	@JsonIgnore
	@ApiModelProperty(value = "具体的异常类", position = 6)
	private Exception realException;

    ....
    ....
}

我用了最简单的方法,重写了该类:

com.github.xiaoymin.swaggerbootstrapui.web.SwaggerBootstrapUiController

我的类:

package cn.boot4j.core.support.swagger;

import static com.google.common.base.Strings.isNullOrEmpty;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE;
import static springfox.documentation.swagger.common.HostNameProvider.componentsFrom;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.util.UriComponents;

import com.github.xiaoymin.swaggerbootstrapui.model.SwaggerBootstrapUiPathInstance;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;

import cn.boot4j.core.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiSort;
import io.swagger.models.Model;
import io.swagger.models.Swagger;
import io.swagger.models.SwaggerBootstrapUi;
import io.swagger.models.SwaggerBootstrapUiPath;
import io.swagger.models.SwaggerBootstrapUiTag;
import io.swagger.models.SwaggerExt;
import io.swagger.models.properties.AbstractProperty;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.service.Documentation;
import springfox.documentation.service.Tag;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.spring.web.json.JsonSerializer;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

@Controller
@ApiIgnore
public class SwaggerUiController {

	/***
	 * sort排序接口
	 */
	public static final String DEFAULT_SORT_URL = "/v2/api-docs-ext";

	private static final String HAL_MEDIA_TYPE = "application/hal+json";
	private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerUiController.class);
	private final ServiceModelToSwagger2Mapper mapper;
	private final DocumentationCache documentationCache;
	private final JsonSerializer jsonSerializer;
	private final String hostNameOverride;

	@Autowired
	public SwaggerUiController(Environment environment, ServiceModelToSwagger2Mapper mapper,
			DocumentationCache documentationCache, JsonSerializer jsonSerializer) {
		this.mapper = mapper;
		this.documentationCache = documentationCache;
		this.jsonSerializer = jsonSerializer;
		this.hostNameOverride = environment.getProperty("springfox.documentation.swagger.v2.host", "DEFAULT");
		;
	}

	@RequestMapping(value = DEFAULT_SORT_URL, method = RequestMethod.GET, produces = { APPLICATION_JSON_VALUE,
			HAL_MEDIA_TYPE })
	@ResponseBody
	public ResponseEntity<Json> apiSorts(@RequestParam(value = "group", required = false) String swaggerGroup,
			HttpServletRequest request) {
		String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
		Documentation documentation = documentationCache.documentationByGroup(groupName);
		if (documentation == null) {
			LOGGER.warn("Unable to find specification for grouRp {}", groupName);
			return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
		}
		Swagger swagger = mapper.mapDocumentation(documentation);
		UriComponents uriComponents = componentsFrom(request, swagger.getBasePath());
		swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
		if (isNullOrEmpty(swagger.getHost())) {
			swagger.host(hostName(uriComponents));
		}


		// >> 扩展~~~~~~~
		swagger = extend(swagger);
        // >> end

		SwaggerExt swaggerExt = new SwaggerExt(swagger);
		// swaggerBootstrapUi.setTagSortLists(getSortTag(request,documentation));
		swaggerExt.setSwaggerBootstrapUi(initSwaggerBootstrapUi(request, documentation));
		// Method 层排序
		return new ResponseEntity<Json>(jsonSerializer.toJson(swaggerExt), HttpStatus.OK);
	}

	@SuppressWarnings("deprecation")
	private SwaggerBootstrapUi initSwaggerBootstrapUi(HttpServletRequest request, Documentation documentation) {
		SwaggerBootstrapUi swaggerBootstrapUi = new SwaggerBootstrapUi();
		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		Iterator<Tag> tags = documentation.getTags().iterator();
		List<SwaggerBootstrapUiTag> targetTagLists = Lists.newArrayList();
		// Ctl层排序
		Map<String, Object> beansWithAnnotation = wc.getBeansWithAnnotation(Controller.class);
		// path排序
		List<SwaggerBootstrapUiPath> targetPathLists = Lists.newArrayList();
		while (tags.hasNext()) {
			Tag sourceTag = tags.next();
			String tagName = sourceTag.getName();
			boolean exists = false;
			Class<?> aClass = null;
			Api api = null;
			for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
				aClass = entry.getValue().getClass();
				api = aClass.getAnnotation(Api.class);
				if (api != null) {
					// 是否相等
					if (Lists.newArrayList(api.tags()).contains(tagName)) {
						exists = true;
						break;
					}
				}
			}
			// 获取order值
			int order = Integer.MAX_VALUE;
			SwaggerBootstrapUiTag tag = new SwaggerBootstrapUiTag(order);
			tag.name(sourceTag.getName()).description(sourceTag.getDescription());
			if (exists) {
				// 优先获取api注解的position属性,如果不等于0,则取此值,否则获取apiSort注解,判断是否为空,如果不为空,则获取apisort的值,优先级:@Api-position>@ApiSort-value
				int post = api.position();
				if (post == 0) {
					ApiSort annotation = aClass.getAnnotation(ApiSort.class);
					if (annotation != null) {
						order = annotation.value();
					}
				} else {
					order = post;
				}
				// targetTagLists.add(new
				// Tag(sourceTag.getName(),sourceTag.getDescription(),order,sourceTag.getVendorExtensions()));
				tag.setOrder(order);
				// 获取父级path
				String parentPath = "";
				RequestMapping parent = aClass.getAnnotation(RequestMapping.class);
				if (parent != null) {
					parentPath = parent.value()[0];
				}
				Method[] methods = aClass.getDeclaredMethods();
				for (Method method : methods) {
					List<SwaggerBootstrapUiPath> paths = new SwaggerBootstrapUiPathInstance(parentPath, method).match();
					if (paths != null && paths.size() > 0) {
						targetPathLists.addAll(paths);
					}
				}
			}
			targetTagLists.add(tag);

		}
		Collections.sort(targetTagLists, new Comparator<SwaggerBootstrapUiTag>() {
			@Override
			public int compare(SwaggerBootstrapUiTag o1, SwaggerBootstrapUiTag o2) {
				return o1.getOrder().compareTo(o2.getOrder());
			}
		});
		Collections.sort(targetPathLists, new Comparator<SwaggerBootstrapUiPath>() {
			@Override
			public int compare(SwaggerBootstrapUiPath o1, SwaggerBootstrapUiPath o2) {
				return o1.getOrder().compareTo(o2.getOrder());
			}
		});

		swaggerBootstrapUi.setTagSortLists(targetTagLists);
		swaggerBootstrapUi.setPathSortLists(targetPathLists);
		return swaggerBootstrapUi;
	}

	private String hostName(UriComponents uriComponents) {
		if ("DEFAULT".equals(hostNameOverride)) {
			String host = uriComponents.getHost();
			int port = uriComponents.getPort();
			if (port > -1) {
				return String.format("%s:%d", host, port);
			}
			return host;
		}
		return hostNameOverride;
	}

	private Swagger extend(Swagger swagger) {
		// 响应返回参数增强
		Iterator<Map.Entry<String, Model>> it = swagger.getDefinitions().entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Model> entry = it.next();
			Model model = entry.getValue();
			String key = entry.getKey();
			if (key.contains("JsonResult")) {
				Map<String, Property> props = model.getProperties();
				Property dataProp = props.get("data");
				if (dataProp.getType().equals("object")) {
					String realType = StringUtil.getRealType(key);
					AbstractProperty newProp = null;
					if (StringUtil.hasRef(key)) { // 存在多级参照
						String ref = StringUtil.getRef(key);
						/** List«T»,Set«T» 支持@See findAll()类型的查询 */
						if (realType.startsWith("List«") || realType.startsWith("Set«")) {
							newProp = new ArrayRefProperty();
							BeanUtils.copyProperties(dataProp, newProp);
							((ArrayRefProperty) newProp).set$ref(ref);
							newProp.setType(ArrayRefProperty.TYPE);
						} else if (realType.startsWith("DBResult«")) { // DBResult«T» 支持@See query()类型的查询
							newProp = new RefProperty();
							BeanUtils.copyProperties(dataProp, newProp);
							((RefProperty) newProp).set$ref(realType);
						} else if (realType.startsWith("Map«")) {
							newProp = new RefProperty();
							BeanUtils.copyProperties(dataProp, newProp);
							((RefProperty) newProp).set$ref(realType);
						} else {
							newProp = new RefProperty();
							BeanUtils.copyProperties(dataProp, newProp);
							((RefProperty) newProp).set$ref(ref);
						}
						// 不存在参照关系,则按常规实际的类型进行处理
					} else if (realType.contains("boolean")) {
						newProp = new BooleanProperty();
						BeanUtils.copyProperties(dataProp, newProp);
						newProp.setType(BooleanProperty.TYPE);
					} else if (realType.contains("string")) {
						newProp = new StringProperty();
						BeanUtils.copyProperties(dataProp, newProp);
						newProp.setType(StringProperty.TYPE);
					} else if (realType.contains("int")) {
						newProp = new IntegerProperty();
						BeanUtils.copyProperties(dataProp, newProp);
						newProp.setType(IntegerProperty.TYPE);
					} else if (realType.contains("map")) {
						newProp = new MapProperty();
						BeanUtils.copyProperties(dataProp, newProp);
					} else if (realType.contains("list")) {
						newProp = new ArrayProperty();
						BeanUtils.copyProperties(dataProp, newProp);
					} else {
						newProp = (AbstractProperty) dataProp;
					}
					props.put("data", newProp);
				}
			}
		}
		return swagger;
	}

}

 关键代码只有1行:

// >> 扩展~~~~~~~
		swagger = extend(swagger);
        // >> end

 运行效果:

Swagger2解决通用返回结果是泛型的问题:swagger2.9.2+ swagger-bootstrap-ui-1.8.5

ArrayRefProperty:

package cn.boot4j.core.support.swagger;

import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.refs.GenericRef;
import io.swagger.models.refs.RefType;

/**
 * 同时拥有ArrayProperty和RefProperty的特性
 * @author ChenZhiPing 2018年10月30日 下午6:08:57
 */
public class ArrayRefProperty extends ArrayProperty {
	private GenericRef genericRef;

	public String get$ref() {
		return genericRef.getRef();
	}

	public void set$ref(String ref) {
		this.genericRef = new GenericRef(RefType.DEFINITION, ref);

		// $ref
		RefProperty items = new RefProperty();
		items.setType(ref);
		items.set$ref(ref);
		this.items(items);
	}
}

 

注意Controller的写法:约定**你我约定**(具体的JsonResult泛型必须指定)

package cn.boot4j.product.demo.web.ui;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

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

import cn.boot4j.core.base.BaseController;
import cn.boot4j.core.support.db.DBResult;
import cn.boot4j.core.support.service.JsonResult;
import cn.boot4j.product.demo.model.customer.Customer;
import cn.boot4j.product.demo.model.customer.CustomerDBParam;
import cn.boot4j.product.demo.service.customer.ICustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


@RestController
@RequestMapping("demo")
@Api(value = "DemoController", tags = { "10.JsonResult响应结果" }, hidden = true)
@SuppressWarnings("unchecked")
public class DemoController extends BaseController {
	@Autowired
	private ICustomerService customerService;

	@ApiOperation(value = "JsonResult«List«T»»", notes = "List类型")
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public JsonResult<List<Customer>> list() {
		try {
			Object data = customerService.findAll();
			return success(data);
		} catch (Exception e) {
			return exception(e);
		}
	}

	@ApiOperation(value = "JsonResult«Map«BaseType, T»»", notes = "Map类型")
	@RequestMapping(value = "map", method = RequestMethod.GET)
	public JsonResult<Map<Integer, Customer>> map() {
		try {
			List<Customer> data = (List<Customer>) customerService.findAll();
			Map<Integer, Customer> map = new HashMap<Integer, Customer>();
			if (data.size() > 0) {
				for (Customer c : data) {
					map.put(c.getId(), c);
				}
			}
			return success(map);
		} catch (Exception e) {
			return exception(e);
		}
	}

	@ApiOperation(value = "JsonResult«Set«T»»", notes = "Set类型")
	@RequestMapping(value = "set", method = RequestMethod.GET)
	public JsonResult<Set<Customer>> set() {
		try {
			List<Customer> data = (List<Customer>) customerService.findAll();
			Set<Customer> set = new TreeSet<>();
			if (data.size() > 0) {
				for (Customer c : data) {
					set.add(c);
				}
			}
			return success(set);
		} catch (Exception e) {
			return exception(e);
		}
	}

	@ApiOperation(value = "JsonResult«DBResult«T»»", notes = "DBResult类型")
	@RequestMapping(value = "query", method = RequestMethod.GET)
	public JsonResult<DBResult<Customer>> query() {
		try {
			Object data = customerService.query(new CustomerDBParam());
			return success(data);
		} catch (Exception e) {
			return exception(e);
		}
	}

	@ApiOperation(value = "JsonResult«BaseType»", notes = "只有基础类型")
	@RequestMapping(value = "deleteByPk", method = RequestMethod.GET)
	public JsonResult<Boolean> deleteByPk() {
		try {
			Object data = customerService.deleteByPk(0);
			return success(data);
		} catch (Exception e) {
			return exception(e);
		}
	}
}