赞
踩
在实际服务端API接口项目开发过程中,会有一些项目约定规范用法Tips,这次整理分享一下我过去使用过的,希望对你有用
1. 接口参数规范
2. 开发代码规范
3. 集成swagger
十分简单、简洁易用的在线接口文档组件swagger
Swagger入门教程用法:SpringBoot从入门到精通教程(二十四)- Swagger集成用法
1. 项目目录结构
2. pom.xml依赖组件
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>com.md</groupId>
- <artifactId>spring-boot2-parent</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <relativePath>../pom.xml</relativePath>
- </parent>
-
- <artifactId>spring-boot2-swagger-req-params</artifactId>
- <packaging>jar</packaging>
-
- <name>spring-boot2-swagger-req-params</name>
- <description>Spring Boot, MVC, Rest API for App</description>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <java.version>1.8</java.version>
- <swagger.version>2.9.2</swagger.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <!-- 构建成可运行的Web项目 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>net.sf.json-lib</groupId>
- <artifactId>json-lib-ext-spring</artifactId>
- </dependency>
- <!-- swagger集成 -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger2</artifactId>
- <version>${swagger.version}</version>
- </dependency>
- <!-- 默认swagger-ui -->
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-swagger-ui</artifactId>
- <version>${swagger.version}</version>
- </dependency>
- <!-- 更易用第三方swagger-ui组件 -->
- <dependency>
- <groupId>com.github.xiaoymin</groupId>
- <artifactId>swagger-bootstrap-ui</artifactId>
- <version>1.9.3</version>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
3. 定义全局header参数
在SwaggerConfig.java文件中,可以新增全局header参数(接口定义本身不需要再重复写了),所有接口会自动带上这个参数,比如userId或者token等
我这里使用了userId,完整代码如下:
- package com.md.demo;
-
- import java.util.ArrayList;
- import java.util.List;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- import springfox.documentation.builders.ApiInfoBuilder;
- import springfox.documentation.builders.ParameterBuilder;
- import springfox.documentation.builders.PathSelectors;
- import springfox.documentation.builders.RequestHandlerSelectors;
- import springfox.documentation.schema.ModelRef;
- import springfox.documentation.service.ApiInfo;
- import springfox.documentation.service.Parameter;
- import springfox.documentation.spi.DocumentationType;
- import springfox.documentation.spring.web.plugins.Docket;
- import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
- @Configuration
- @EnableSwagger2
- public class SwaggerConfig {
-
- /**
- * 创建一个Docket对象 调用select()方法, 生成ApiSelectorBuilder对象实例,该对象负责定义外漏的API入口
- * 通过使用RequestHandlerSelectors和PathSelectors来提供Predicate,在此我们使用any()方法,将所有API都通过Swagger进行文档管理
- *
- * @return
- */
- @Bean
- public Docket createRestApi() {
- // 定义全局header参数
- ParameterBuilder useridPar = new ParameterBuilder();
- List<Parameter> pars = new ArrayList<>();
- useridPar.name("userId").defaultValue("").description("用户id").modelRef(new ModelRef("string"))
- .parameterType("header").required(false).build();
- pars.add(useridPar.build());
-
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo()).select()
- //如果不想将所有的接口都通过swagger管理的话,可以将RequestHandlerSelectors.any()修改为RequestHandlerSelectors.basePackage()
- //.apis(RequestHandlerSelectors.any())
- .apis(RequestHandlerSelectors.basePackage("com.md"))
- .paths(PathSelectors.any())
- .build()
- .globalOperationParameters(pars);
- }
-
- @SuppressWarnings("deprecation")
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- // 标题
- .title("SpringBoot2 中使用Swagger2 构建RESTful APIs")
- // 简介
- .description("This a demo for Swagger2")
- // 服务条款
- .termsOfServiceUrl("https://blog.csdn.net/hemin1003")
- // 作者个人信息
- .contact("Minbo.He")
- // 版本
- .version("1.0").build();
- }
- }
4. 定义DTO参数对象
GetByIdDTO.java
- package com.md.demo.dto;
-
- import javax.validation.constraints.NotEmpty;
-
- import io.swagger.annotations.ApiModel;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.Data;
-
- @Data
- @ApiModel("根据用户ID标识查询")
- public class GetByIdDTO {
-
- @ApiModelProperty(value = "用户ID标识", required = true)
- @NotEmpty(message = "用户ID标识不能为空")
- private String id;
- }
5. 定义一个接口基类
BaseController.java,接收参数合法性校验结果
- package com.md.demo.util;
-
- import java.util.List;
-
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.ObjectError;
-
- /**
- * 基类
- *
- * @author Minbo
- *
- */
- public class BaseController {
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public JsonResult getJsonResult(Object model, BindingResult result) {
- if (result.hasErrors()) {
- StringBuilder stringBuilder = new StringBuilder();
- List<ObjectError> allErrors = result.getAllErrors();
- for (ObjectError objectError : allErrors) {
- String defaultMessage = objectError.getDefaultMessage();
- // 验证失败时提示内容一起拼接返回
- stringBuilder.append(defaultMessage).append(";");
- }
- return new JsonResult(CodeEnums.PARA_ERR.getCode(), stringBuilder.toString(), model);
- }
- return null;
- }
- }
6. 定义一个http状态码工具类
HttpStatusCodeUtil.java
- package com.md.demo.util;
-
- import javax.servlet.http.HttpServletResponse;
-
- import lombok.extern.slf4j.Slf4j;
-
- /**
- * http响应码工具类
- *
- * @author Minbo
- *
- */
- @Slf4j
- public class HttpStatusCodeUtil {
-
- /**
- * 设置http响应码
- *
- * @param response
- * @param statusCode
- */
- public static void setCode(HttpServletResponse response, Integer statusCode) {
- try {
- response.setStatus(statusCode);
- } catch (Exception ex) {
- log.error("设置http响应码异常:" + ex.getMessage(), ex);
- }
- }
- }
7. 接口访问层(@RequestHeader和@RequestBody)
InitController.java
- package com.md.demo.rest;
-
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.bind.annotation.RequestHeader;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import com.md.demo.util.JsonResult;
-
- import io.swagger.annotations.ApiImplicitParam;
- import io.swagger.annotations.ApiOperation;
-
- /**
- * @author Minbo
- */
- @RestController
- public class InitController {
-
- protected static Logger logger = LoggerFactory.getLogger(InitController.class);
-
- /**
- * http://localhost:9090/hello
- *
- * @return
- */
- @ApiOperation(value = "/hello 欢迎入口", httpMethod = "GET")
- @RequestMapping(value = "/hello")
- public String hello() {
- logger.info("hello");
- return "Hello greetings from spring-boot2-swagger-req-params";
- }
-
- @ApiOperation(value = "/getUserName 根据用户id获得用户的姓名", notes = "id不能为空", httpMethod = "GET")
- @ApiImplicitParam(dataType = "string", name = "userId", value = "用户id", required = true)
- @RequestMapping(value = "/getUserName")
- @SuppressWarnings({ "rawtypes" })
- public JsonResult getUserName(@RequestHeader String userId) {
- String result = "hello " + userId + ",name=张三";
- return JsonResult.ok(result);
- }
-
- /**
- * Swagger注解用法:
- *
- * @Api:修饰整个类,描述Controller的作用
- * @ApiOperation:描述一个类的一个方法,或者说一个接口
- * @ApiParam:单个参数描述
- * @ApiModel:用对象来接收参数
- * @ApiProperty:用对象接收参数时,描述对象的一个字段
- * @ApiResponse:HTTP响应其中1个描述
- * @ApiResponses:HTTP响应整体描述
- * @ApiIgnore:使用该注解忽略这个API
- * @ApiError :发生错误返回的信息
- * @ApiImplicitParam:一个请求参数
- * @ApiImplicitParams:多个请求参数
- */
- }
DemoController.java
- package com.md.demo.rest;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.annotation.Validated;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import com.md.demo.dto.GetByIdDTO;
- import com.md.demo.service.IUserService;
- import com.md.demo.util.BaseController;
- import com.md.demo.util.HttpStatusCodeUtil;
- import com.md.demo.util.JsonResult;
- import com.md.demo.vo.UserVO;
-
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import lombok.extern.slf4j.Slf4j;
-
- /**
- * @author Minbo
- */
- @RestController
- @RequestMapping("/demo")
- @Api(tags = { "接口-演示" })
- @Slf4j
- public class DemoController extends BaseController {
-
- @Autowired
- private IUserService userService;
-
- @ApiOperation(value = "根据id获得用户信息", notes = "id不能为空", httpMethod = "POST")
- @PostMapping(value = "/getUserById")
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public JsonResult<UserVO> getUserById(@Validated @RequestBody GetByIdDTO dto, BindingResult result,
- HttpServletRequest request, HttpServletResponse response) {
- // 验证参数合法性(@NotEmpty注解)
- JsonResult validResult = super.getJsonResult(dto, result);
- if (validResult != null) {
- // 设置http响应码,利于监控工具,不要统一使用200
- HttpStatusCodeUtil.setCode(response, 4403);
- return validResult;
- }
-
- // 获取用户ID
- String userId = request.getHeader("userId");
- log.info("获取用户ID,userId={}", userId);
-
- // 逻辑处理
- UserVO obj = this.userService.getUserById(dto);
- return JsonResult.ok(obj);
- }
- }
说明:
1. 接口自动增加了全局header参数
2. 接口body参数用法,以及自动附加了接口数据模型说明
返回数据模型说明:UserVO.java类
3. 接口成功时:响应返回内容
各个字段及内容,会自动映射对应上,客户端接入时简单、高效
4. 接口异常时:响应返回内容
SpringBoot从入门到精通教程(二十七)- @Valid注解用法详解+全局处理器Exception优雅处理参数验证用法
Swagger入门教程用法:SpringBoot从入门到精通教程(二十四)- Swagger集成用法
至此,全部介绍就结束了
-------------------------------
-------------------------------
关于我(个人域名)
期望和大家一起学习,一起成长,共勉,O(∩_∩)O谢谢
欢迎交流问题,可加个人QQ 469580884,
或者,加我的群号 751925591,一起探讨交流问题
不讲虚的,只做实干家
Talk is cheap,show me the code
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。