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();
}
}