美文网首页
RestFul 通用接口设计

RestFul 通用接口设计

作者: 潜心之力 | 来源:发表于2020-03-29 15:58 被阅读0次
    一、API接口统一返回类
    • 定义接口通用的结果返回类JsonResult,其中包括请求状态码(code)、请求信息(msg)、请求数据集(obj),定义通用的状态返回枚举JsonEnum,其中包含请求状态码以及该状态码对应的请求信息。
    • 实战,定义对应的Controller、Service、Dao、Entity,非事务逻辑校验可以在Controller或者Service中进行校验,事务逻辑必须在Service中校验,如不符合条件的情况下可以通过抛出异常的方式来终止事务,使事务发生回滚,保持数据的原子性。
    public class JsonResult {
    
        private Integer code;
        private String msg;
        private Object obj;
    
        public static JsonResult result(JsonEnum en,Object obj) {
            JsonResult result = new JsonResult();
            result.code = en.getCode();
            result.msg = en.getMsg();
            result.obj = obj;
            return result;
        }
    }
    
    public enum JsonEnum {
        REQUEST_SUCCESS(200,"请求成功"),
        REQUEST_FAIL(500,"请求失败");
    
        private Integer code;
        private String msg;
    
        JsonEnum(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
    
    @RestController
    @RequestMapping("/system/user")
    public class SystemUserController{
    
        @Autowired
        private ISystemUserService mSystemUserService;
    
        @PostMapping(value = "/insert")
        public JsonResult insert(SystemUser user){
            try {
                return mSystemUserService.insert(user);
            } catch (Exception e) {
                return JsonResult.result(JsonEnum.REQUEST_FAIL,e.getMessage());
            }
        }
    }
    
    public interface ISystemUserService {
        JsonResult insert(SystemUser user) throws Exception;
    }
    
    @Service
    @Transactional
    public class SystemUserServiceImpl implements ISystemUserService {
    
        @Autowired
        private SystemDao mSystemDao;
    
        @Override
        public JsonResult insert(SystemUser user) throws Exception {
            if(StringUtils.isEmpty(user.getName())){
                throw new RuntimeException("用户名不允许为空"); -> 抛出异常,事务回滚
            }
            return JsonResult.result(JsonEnum.REQUEST_SUCCESS, mSystemDao.insert(user));
        }
    }
    
    二、API接口查看文档
    <dependencies>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
    ​
        <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger2</artifactId>
           <version>2.9.2</version>
        </dependency>
    </dependencies>
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    ​
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    ​
    @Configuration  
    @EnableSwagger2
    public class Swagger2Configuration {
    
       @Bean
       public Docket createRestApi() {
           return new Docket(DocumentationType.SWAGGER_2)
                      .apiInfo(apiInfo())
                      .select()
                      .apis(RequestHandlerSelectors
                      .basePackage("com.wjx.controller")) 
                      .paths(PathSelectors.any())
                      .build();
       }
    ​
       private ApiInfo apiInfo() {
           return new ApiInfoBuilder()
                      .title("标题")
                      .description("接口文档")
                      .version("1.0.0")
                      .termsOfServiceUrl("官方网站")
                      .build();
       }
    }
    
    localhost:8080/swagger-ui.html -> swagger在线文档
    
    import io.swagger.annotations.*;
    import org.springframework.web.bind.annotation.*;
    
    @Api("用户信息管理")
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private IUserService mUserService;
    
        @ApiOperation(value = "查询用户信息",notes = "允许用户不存在",response = User.class)
        @ApiResponse(code = 200,message = "请求成功")
        @ApiImplicitParam(name = "id", value = "用户唯一标识", paramType = "path")
        @RequestMapping("/select")
        public User select(Integer id) {
            return mUserService.selectUserById(id);
        }
    }
    
    @ApiModel("用户实体类") -> 默认为第一个注解方法赋值
    class User {
        @ApiModelProperty(value = "用户唯一标识",name = "id",dataType = "integer",example = "1")
        private Integer id;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    }
    
    paramType: -> 参数获取方式
      header: @RequestHeader
      query: @RequestParam
      path: @PathVariable
      body: @RequestBody
      form: 少用
    
    注解 含义 示例
    @Api 描述API类,标识为swagger资源 @Api(value="描述",hidden=false)
    @ApiOperation 描述API方法的用途 @ApiOperation(value="描述",notes="备注",response="返回数据类型",hidden=false)
    @ApiParam 描述对象入参 @ApiParam(name="参数名",value="描述",defaultValue="默认值",type="参数类型",example="举例",required=false,hidden=false)
    @ApiImplicitParam 描述非对象入参 @ApiImplicitParam(name="参数名",value="描述",paramType="参数从哪个域获取",dataType="参数类型",defaultValue="默认值",required=true)
    @ApiImplicitParams 描述非对象入参集 @ApiImplicitParams({@ApiImplicitParam})
    @ApiModel 描述POJO类的用途 @ApiModel(value="名称",description="描述")
    @ApiModelProperty 描述POJO类成员变量的用途 @ApiModelProperty(value="描述",name="变量名称",dataType="数据类型",example="举例",required=true,hidden=false)
    @ApiResponse 描述方法的一个响应信息 @ApiResponse(code=404,message="页面没有找到")
    @ApiResponses 描述方法的一组响应信息 @ApiResponses({@ApiResponse(code=200,message="成功"),@ApiResponse(code=500,message="失败")})
    @ApiIgnore 忽略当前方法接口 @ApiIgnore

    相关文章

      网友评论

          本文标题:RestFul 通用接口设计

          本文链接:https://www.haomeiwen.com/subject/hkluuhtx.html