【Java】拒绝重复代码,从我做起,下面介绍4种方法

1,if -else 判断校验去除重复代码
public ResponseInfo check() {
        String name = "张三";
        if (StringUtil.isBlank(name)) {
            return ResponseInfo.failMsg(ErrorCode.MANAGE_LEVEL_ERROR_CODE);
        }
        if (StringUtil.isBlank(name)) {
            return ResponseInfo.failMsg(ErrorCode.MANAGE_LEVEL_ERROR_CODE);
        }
        if (StringUtil.isBlank(name)) {
            return ResponseInfo.failMsg(ErrorCode.MANAGE_LEVEL_ERROR_CODE);
        }
        if (StringUtil.isBlank(name)) {
            return ResponseInfo.failMsg(ErrorCode.MANAGE_LEVEL_ERROR_CODE);
        }
        if (StringUtil.isBlank(name)) {
            return ResponseInfo.failMsg(ErrorCode.MANAGE_LEVEL_ERROR_CODE);
        }
        return ResponseInfo.successData();
    }
    
    public static class Assert{
        public static ResponseInfo<T> isBlank(String str,Object... msg){
            if (StringUtil.isBlank(str)) {
                return ResponseInfo.successData();
            } else {
                ResponseInfo<T> responseInfo = new ResponseInfo<>();
                responseInfo.setSuccess(false);
                responseInfo.setMsg(MessageFormat.format(str, msg));
                responseInfo.setCode("10010");
                return responseInfo;  
            }
        }
    }

    public static void main(String[] args) {
        String name = "张三";
        Assert.isBlank(name, "姓名");
    }
}
2,SpringBoot注解校验去除重复代码

在校验的参数前面加上@Valid ,然后在需要校验的参数实体类加上校验注解@NotNull等等 需要注意的是@Vaild只能作用于实体类基础数据类型是不能校验成功的只能作用于对象类型

  public static ResponseInfo<T> isBlank(String str, @Valid User user){
        if (StringUtil.isBlank(str)) {
            return ResponseInfo.successData();
        }
        return ResponseInfo.successData();
    }
    
    @Data
    public class User{
        @NotBlank(message = "用户名不为空")
        String username;
        @NotBlank(message = "用户id不为空")
        String userId;
    }
3,实体类继承父类属性

作用于实体类定义时一些基础属性可以抽出来做父类避免重复去写在每个实体里面,之类继承就可以了

    @Data
    public class Base {

        String createUser;
        String updateUser;
        Date createTime;
        Date updateTime;

    }

    @Data
    public class User extends Base {

        @NotBlank(message = "用户名不为空")
        String username;
        @NotBlank(message = "用户id不为空")
        String userId;
    }
4,自定义注解去除重复代码

下面简单介绍一种获取接口执行时间的自定义注解提供参考

public class TaskAspect {
    ThreadLocal<Long> taskData = new ThreadLocal<>();
    Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("@annotation(com.tencent.hr.corehr.common.annotation.TaskMonitor)")
    public void pointCut(){}
    @Before("pointCut()")
    public void beforeHandle(JoinPoint joinPoint) {
        taskData.set(System.currentTimeMillis());
        String taskName = getTaskName(joinPoint);
        logger.info(DateUtil.now()+" "+taskName+"方法开始执行");
    }

    @After("pointCut()")
    public void afterHandle(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        TaskMonitor annotation = method.getAnnotation(TaskMonitor.class);
        long errTime = annotation.errTime();

        long time=System.currentTimeMillis()-taskData.get();
        String taskName = getTaskName(joinPoint);
        if(time > errTime){
            logger.error(taskName+"执行时间大于5分钟,请注意,共耗时:"+time/1000+"秒");
        }
        logger.info(DateUtil.now()+" "+taskName+"方法结束执行,耗时" + time +"ms");
    }

    /**
     * 获取定时任务类加名字
     */
    private String getTaskName(JoinPoint joinPoint){
        return joinPoint.getTarget().getClass().getSimpleName()+"."+joinPoint.getSignature().getName();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值