SpringBoot项目中Controller层代码编写规范整理

Controller层代码规范

主要的内容是就是接口定义里面的内容,你只要遵循里面的规范,controller就问题不大,除了这些,还有另外的几点:

  1. 所有函数返回统一的ResultBean/PageResultBean格式;
  2. 没有统一格式,AOP无法玩.
  3. ResultBean/PageResultBean是controller专用的,不允许往后传
  4. Controller做参数格式的转换,不允许把json,map这类对象传到services去,也不允许services返回json、map。

SpringMVC接口定义要注意以下常见的几种问题

1. 返回格式不统一

同一个接口,有时候返回数组,有时候返回单个;成功的时候返回对象,失败的时候返回错误信息字符串。工作中有个系统集成就是这样定义的接口,真是辣眼睛。这个对应代码上,返回的类型是map,json,object,都是不应该的。实际工作中,我们会定义一个统一的格式,就是ResultBean,分页的有另外一个PageResultBean
错误范例:

    //返回map可读性不好,尽量不要 
    @PostMapping("/delete") 
    public Map<String, Object> delete(long id, String lang) { } 
    // 成功返回boolean,失败返回string,大忌 
    @PostMapping("/delete") 
    public Objectdelete(long id, String lang) { 
        try { 
            boolean result = configService.delete(id, local); return result; 
        } catch (Exception e) {
            log.error(e); return e.toString(); 
        } 
    }

2. 没有考虑失败情况

一开始只考虑成功场景,等后面测试发现有错误情况,怎么办,改接口呗,前后台都改,劳民伤财无用功。
错误范例:

//不返回任何数据,没有考虑失败场景,容易返工 PostMapping("/update") public void update(long id, xxx) { }

3. 出现和业务无关的输入参数

如lang语言,当前用户信息 都不应该出现参数里面,应该从当前会话里面获取。后面讲ThreadLocal会说到怎么样去掉。除了代码可读性不好问题外,尤其是参数出现当前用户信息的,这是个严重问题。
错误范例:

// (当前用户删除数据)参数出现lang和userid,尤其是userid,大忌 PostMapping("/delete") 
public Map<String, Object> delete(long id,String lang, String userId) { }
  1. 出现复杂的输入参数
    一般情况下,不允许出现例如json字符串这样的参数,这种参数可读性极差。应该定义对应的bean。
    错误范例:
// 参数出现json格式,可读性不好,代码也难看 PostMapping("/update") public Map<String, Object> update(long id, String jsonStr) { }
  1. 没有返回应该返回的数据
    例如,新增接口一般情况下应该返回新对象的id标识,这需要编程经验。新手定义的时候因为前台没有用就不返回数据或者只返回true,这都是不恰当的。别人要不要是别人的事情,你该返回的还是应该返回。
    错误范例:
// 约定俗成,新建应该返回新对象的信息,只返回boolean容易导致返工 PostMapping("/add") 
public boolean add(xxx) { //xxx return configService.add(); }

很多人看了我的这篇文章程序员你为什么这么累?,都觉得里面的技术也很简单,没有什么特别的地方,但是,实现这个代码框架之前,就是要你的接口的统一的格式ResultBean,aop才好做。有些人误解了,我那篇文章说的都不是技术,重点说的是编码习惯工作方式,如果你重点还是放在什么技术上,那我也帮不了你了。同样,如果我后面的关于习惯和规范的帖子,你重点还是放在技术上的话,那是丢了西瓜捡芝麻,有很多贴还是没有任何技术点呢。
附上ResultBean,没有任何技术含量:


/**
 * Controller统一返回对象,响应信息主体
 */
@Getter
@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 状态码:1成功,其他均为失败【详见错误状态码表】
     */
    @ApiModelProperty(value = "状态码")
    private int code;
    /**
     * 成功为success,其他为失败原因
     */
    @ApiModelProperty(value = "消息")
    private Object message = "success";
    /**
     * 数据结果集
     */
    @ApiModelProperty(value = "数据结果集")
    private T data;
    /**
     * 当前时间
     */
    @ApiModelProperty(value = "时间戳")
    private final long time = System.currentTimeMillis();

    public R<T> setMessage(Object message) {
        this.message = message;
        return this;
    }

    public R<T> setMessage(String format, Object... args) {
        this.message = new Formatter().format(format, args).toString();
        return this;
    }

    public R() {
    }

    /**
     * 使用枚举类中模版消息
     *
     * @param resultConstant ResultConstant
     * @param data           数据结果集
     */
    private R(ResultConstant resultConstant, T data) {
        this.code = resultConstant.getCode();
        this.message = resultConstant.getMessage();
        this.data = data;
    }

    public static <T> R<T> ok() {
        return restResult(ResultConstant.SUCCESS, null, null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(ResultConstant.SUCCESS, null, data);
    }

    public static <T> R<T> ok(T data, Object message) {
        return restResult(ResultConstant.SUCCESS, message, data);
    }

    public static <T> R<T> failed(ResultConstant resultConstant) {
        return restResult(resultConstant, null, null);
    }

    public static <T> R<T> failed(ResultConstant resultConstant, Object message) {
        return restResult(resultConstant, message, null);
    }

    public static <T> R<T> failed(ResultConstant resultConstant, Object message, T data) {
        return restResult(resultConstant, message, data);
    }

    private static <T> R<T> restResult(ResultConstant resultConstant, Object message, T data) {
        R<T> apiResult = new R<>(resultConstant, data);
        if (null != message) {
            apiResult.setMessage(message);
        }
        return apiResult;
    }
}

统一的接口规范,能帮忙规避很多无用的返工修改和可能出现的问题。能使代码可读性更加好,利于进行aop和自动化测试这些额外工作。

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
- chapter1:[基本项目构建(可作为工程脚手架),引入web模块,完成一个简单的RESTful API](http://blog.didispace.com/spring-boot-learning-1/) - [使用Intellij的Spring Initializr来快速构建Spring Boot/Cloud工程](http://blog.didispace.com/spring-initializr-in-intellij/) ### 工程配置 - chapter2-1-1:[配置文件详解:自定义属性、随机数、多环境配置等](http://blog.didispace.com/springbootproperties/) ### Web开发 - chapter3-1-1:[构建一个较为复杂的RESTful API以及单元测试](http://blog.didispace.com/springbootrestfulapi/) - chapter3-1-2:[使用Thymeleaf模板引擎渲染web视图](http://blog.didispace.com/springbootweb/) - chapter3-1-3:[使用Freemarker模板引擎渲染web视图](http://blog.didispace.com/springbootweb/) - chapter3-1-4:[使用Velocity模板引擎渲染web视图](http://blog.didispace.com/springbootweb/) - chapter3-1-5:[使用Swagger2构建RESTful API](http://blog.didispace.com/springbootswagger2/) - chapter3-1-6:[统一异常处理](http://blog.didispace.com/springbootexception/) ### 数据访问 - chapter3-2-1:[使用JdbcTemplate](http://blog.didispace.com/springbootdata1/) - chapter3-2-2:[使用Spring-data-jpa简化数据访问层(推荐)](http://blog.didispace.com/springbootdata2/) - chapter3-2-3:[多数据源配置(一):JdbcTemplate](http://blog.didispace.com/springbootmultidatasource/) - chapter3-2-4:[多数据源配置(二):Spring-data-jpa](http://blog.didispace.com/springbootmultidatasource/) - chapter3-2-5:[使用NoSQL数据库(一):Redis](http://blog.didispace.com/springbootredis/) - chapter3-2-6:[使用NoSQL数据库(二):MongoDB](http://blog.didispace.com/springbootmongodb/) - chapter3-2-7:[整合MyBatis](http://blog.didispace.com/springbootmybatis/) - chapter3-2-8:[MyBatis注解配置详解](http://blog.didispace.com/mybatisinfo/) ### 事务管理 - chapter3-3-1:[使用事务管理](http://blog.didispace.com/springboottransactional/) - chapter3-3-2:[分布式事务(未完成)] ### 其他内容 - chapter4-1-1:[使用@Scheduled创建定时任务](http://blog.didispace.com/springbootscheduled/) - chapter4-1-2:[使用@Async实现异步调用](http://blog.didispace.com/springbootasync/) #### 日志管理 - chapter4-2-1:[默认日志的配置](http://blog.didispace.com/springbootlog/) - chapter4-2-2:[使用log4j记录日志](http://blog.didispace.com/springbootlog4j/) - chapter4-2-3:[对log4j进行多环境不同日志级别的控制](http://blog

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CHQIUU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值