为手机端app定义接口,原先是定义接口文档,然后在使用postman测试接口的可用性,觉得这个非常麻烦,曾有一会接口文档还造成的误删的情况。所以抽空将所有的接口swagger2进行管理接口。添加成功后,记录一下该方法的实现方式,以便后期查看使用。
一:pom文件引入
<!-- swagger2核心依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- swagger-ui为项目提供api展示及测试的界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
二:创建SwaggerConfig.java
/**
* @Title: ApiConfig.java
* @Prject: qikanchina-web-admin-war
* @Package: com.qikanchina.system.config
* @Description: TODO
* @author: 豫东一颗草
* @date: 2019年7月26日 上午9:59:13
* @version: V1.0
* Copyright © 2019 . All rights reserved.
*/
package com.changjiu.system.config;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
/**
* @Description: swagger config
* @author 豫东一颗草
* @Date 2019年7月26日 上午9:59:13
*/
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
/**
* 创建API应用 两种实现方式,其中第一种较为简单明了
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket createRestApi() {
// return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any()) //这里填写controller类路径
// .paths(PathSelectors.regex(".*.*"))//这里有路径匹配包含正则,才可以生成文档,暂时设置为空
// .build();
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(SwaggerConfig.basePackage("com.changjiu.web.action"))//设置扫描特定包,如果有多个中间用','隔开。如:com.changjiu.web.action,com.changjiu.web.action1
.paths(PathSelectors.any()).build();
}
/**
* @Description: 处理程序的方法和基类
* @date:2019年7月29日 上午9:55:46
* @Title: basePackage
* @param basePackage
* @return
*/
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
};
}
/**
* 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
*
* @param basePackage 扫描包路径
* @return Function
*/
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return new Function<Class<?>, Boolean>() {
@Override
public Boolean apply(Class<?> input) {
for (String strPackage : basePackage.split(",")) {
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
}
};
}
/**
* @Description: 判断是否为空值
* @date:2019年7月29日 上午10:03:51
* @Title: declaringClass
* @param input
* @return
*/
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("九九车圈接口").description("这就是一个描述").termsOfServiceUrl("http://www.baidu.com")
.contact("豫东一颗草").version("1.0.0").build();
}
}
三:springMVC注入config.
<!-- swagger 配置 ,线上版本需要注释掉 -->
<bean class="com.changjiu.system.config.SwaggerConfig"/>
四:controller实现
/**
* @Title: LogisticsOrderAction.java
* @Prject: changjiu-web-war
* @Package: com.changjiu.web.action
* @Description: 物流订单
* @author: 豫东一颗草
* @date: 2019年7月19日 上午8:48:09
* @version: V1.0
* Copyright © 2019 . All rights reserved.
*/
package com.changjiu.web.action;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.changjiu.car.order.invoice.model.CjLogisticsInvoice;
import com.changjiu.car.order.invoice.service.CjLogisticsInvoiceService;
import com.changjiu.car.order.logiaddress.model.CjLogisticsAddress;
import com.changjiu.car.order.logiaddress.service.CjLogisticsAddressService;
import com.changjiu.car.order.logisticsCar.model.LogisticsCar;
import com.changjiu.car.order.logisticsCar.service.LogisticsCarService;
import com.changjiu.car.order.order.model.CjLogisticsOrder;
import com.changjiu.car.order.order.service.CjLogisticsOrderService;
import com.changjiu.common.enums.YesOrNoEnum;
import com.changjiu.common.framework.result.MobileResult;
import com.changjiu.common.utils.Contants;
import com.changjiu.common.utils.HttpClientUtil;
import com.changjiu.common.utils.ObjectUtil;
import com.changjiu.commons.collect.MapUtils;
import com.changjiu.commons.utils.JSONUtils;
import com.changjiu.commons.utils.PropertyConfig;
import com.changjiu.commons.utils.UUIDUtils;
import com.changjiu.system.base.BaseController;
import com.changjiu.web.dto.OrderDto;
import com.google.common.collect.Maps;
/**
* @Description: 物流订单的相关功能
* @author 豫东一颗草
* @Date 2019年7月19日 上午8:48:09
*/
@Api(description = "物流订单相关功能")
@CrossOrigin
@RestController
@RequestMapping(value = LogisticsOrderAction.BASE_VIEW)
public class LogisticsOrderAction extends BaseController {
public static final String BASE_VIEW = "/logistics/order";
@Autowired
@Qualifier("logistics.CjLogisticsAddressService")
private CjLogisticsAddressService cjLogisticsAddressService;
@Autowired
@Qualifier("logistics.LogisticsCarService")
private LogisticsCarService logisticsCarService;
/**
* wl-1012
* @Description: 获取收车地址信息/发车地址信息列表
* @date:2019年7月19日 下午1:20:40
* @Title: updateAddress
* @param request
* @param response
* @return
*/
@ApiOperation(value = "获取当前登陆用户最新收车地址/发车地址详情", httpMethod = "POST")
@ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "登陆签名", required = true, paramType = "form"),
@ApiImplicitParam(name = "datatype", value = "数据类型", required = true, paramType = "form") })
@RequestMapping(value = "/selectByUserIdAndTypeLoginInt", method = RequestMethod.POST)
public Map<String, Object> selectByUserIdAndTypeLoginInt(HttpServletRequest request, HttpServletResponse response) {
createParameterMap(request);
String userId = "-1";
try {
String dataType = paramsMap.get("datatype").toString();
String code = request.getSession().getAttribute("code").toString();
if (Objects.equals(code, Contants.TOKEN_IS_SUCCESS)) {
userId = request.getSession().getAttribute("userId").toString();
} else {
return MobileResult.error(Contants.TOKEN_IS_ERROR, Contants.TOKEN_IS_ERROR_MSG);
}
List<CjLogisticsAddress> address = cjLogisticsAddressService.selectByUserIdAndDataType(userId, dataType);
return MobileResult.success(address);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
return MobileResult.error(Contants.IS_FAILE, Contants.IS_FAILE_MSG);
}
}
/**
* wl-1013 存储订单接口
* @Description: 存储订单信息
* @date:2019年7月19日 下午1:20:40
* @Title: updateAddress
* @param request
* @param response
* @return
*/
@ApiOperation(value = "wl-1013 存储订单接口", httpMethod = "POST")
@ApiImplicitParams({ @ApiImplicitParam(name = "token", value = "登陆签名", required = true, paramType = "form"),
@ApiImplicitParam(name = "data", value = "存储类型", required = true, paramType = "form") })
@RequestMapping(value = "/addOrderLoginInt", method = RequestMethod.POST)
public Map<String, Object> addOrderLoginInt(HttpServletRequest request, HttpServletResponse response) {
createParameterMap(request);
String userId = "-1";
Date date = new Date();
try {
String data = paramsMap.get("data").toString();
JSONObject jsonObj = JSONObject.fromObject(data);
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("cars", LogisticsCar.class);
OrderDto orderDto = (OrderDto) JSONObject.toBean(jsonObj, OrderDto.class, classMap);
// JsonConfig config = new JsonConfig();
// config.setJavaIdentifierTransformer(new JavaIdentifierTransformer() {
// @Override
// public String transformToJavaIdentifier(String paramString) {
// char[] chars = paramString.toCharArray();
// chars[0] = Character.toLowerCase(chars[0]);
// System.out.println("****************************");
// System.out.println(new String(chars));
// return new String(chars);
// }
// });
// config.setRootClass(OrderDto.class);
// OrderDto p2 = (OrderDto) JSONObject.toBean(jsonObj, config);
String code = request.getSession().getAttribute("code").toString();
if (Objects.equals(code, Contants.TOKEN_IS_SUCCESS)) {
userId = request.getSession().getAttribute("userId").toString();
} else {
return MobileResult.error(Contants.TOKEN_IS_ERROR, Contants.TOKEN_IS_ERROR_MSG);
}
/*获取订单的Id*/
String orderId = UUIDUtils.getUUID();
/* 1、添加发票信息 ,如果该订单不需要发票信息,则不用存储*/
String logisticsInvoiceId = "-1";
if (Objects.equals(orderDto.getNeedTicketFlag(), YesOrNoEnum.YES.key())) {
CjLogisticsInvoice logisticsInvoice = orderDto.getCustInvoiceVo();
logisticsInvoiceId = UUIDUtils.getUUID();
logisticsInvoice.setId(logisticsInvoiceId);
logisticsInvoice.setOrderId(orderId);
logisticsInvoice.setCrtTime(date);
int i = cjLogisticsInvoiceService.addCjLogisticsInvoice(logisticsInvoice);
//发票信息存储失败
if (i < 1) {
return MobileResult.error(Contants.IS_FAILE, Contants.IS_FAILE_MSG);
}
}
/* 2、添加车辆管理信息 addVehicleInfoList */
List<LogisticsCar> carDtos = orderDto.getCars();
// List<LogisticsCar> logisticsCars = Lists.transform(carDtos, new Function<LogisticsCarDto, LogisticsCar>() {
// @Override
// public LogisticsCar apply(LogisticsCarDto carDto) {
// LogisticsCar car = new LogisticsCar();
// BeanUtils.copyProperties(carDto, car);
// car.setCrtTime(date);
// return car;
// }
// });
int j = logisticsCarService.addVehicleInfoList(carDtos, orderId);
/* 3、添加订单信息 */
CjLogisticsOrder orderEntity = new CjLogisticsOrder();
BeanUtils.copyProperties(orderDto, orderEntity);
orderEntity.setId(orderId);
orderEntity.setCrt_time(date);
orderEntity.setUserId(userId);
orderEntity.setCustInvoiceId(logisticsInvoiceId);
orderEntity.setIsDelete((byte) 0);
int k = cjLogisticsOrderService.addCjLogisticsOrder(orderEntity);
if (j > 0 && k > 0) {
return MobileResult.success(1);
} else {
return MobileResult.error(Contants.IS_FAILE, Contants.IS_FAILE_MSG);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
return MobileResult.error(Contants.IS_FAILE, Contants.IS_FAILE_MSG);
}
}
}
五:完成
备注:非常简单,只要按照步骤,轻松搞定。controller种的注解使用方法请自行查找学习。