RestFul 通用接口设计

2020-03-29  本文已影响0人  潜心之力
一、API接口统一返回类
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
上一篇下一篇

猜你喜欢

热点阅读