项目请求时,在controller里面做一大堆非空判断,真是繁琐低效.加个注解一次性解决问题
1. 自定义注解@CheckNull
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckNull {
String[] value() default {};
}
2. 对@CheckNull进行解析
package com.lyf.aop;
import com.lyf.annotation.CheckNull;
import com.lyf.base.Constant;
import com.lyf.exception.ParamsException;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
@Slf4j
public class CheckNullAspect {
@Autowired
HttpServletRequest request;
@Before("@annotation(com.lyf.annotation.CheckNull) && @annotation(checkNull)")
public void check(JoinPoint jp, CheckNull checkNull) throws Throwable {
String[] checkNames = checkNull.value();
Map<String, String> paramMap = getParamMap(jp);
for (int i = 0; i < checkNames.length; i++) {
String checkName = checkNames[i];
if(StringUtils.isBlank(paramMap.get(checkName))
&& StringUtils.isBlank(request.getParameter(checkName))){// 兼容通过对象获取参数形式
throw new ParamsException(Constant.ERROR_CODE, checkName+"不能为空");
}
}
}
/**
* 获取请求参数列表
* @return
*/
private Map<String, String> getParamMap(JoinPoint jp) {
Object[] argArr = jp.getArgs();
MethodSignature signature = (MethodSignature) jp.getSignature();
String[] paramNameArr = signature.getParameterNames();
Map<String, String> paramMap = new HashMap<>();
for (int i = 0; i < paramNameArr.length; i++) {
paramMap.put(paramNameArr[i], ObjectUtils.nullSafeToString(argArr[i]));
}
return paramMap;
}
}
3. 自定义异常类ParamsException
package com.lyf.exception;
public class ParamsException extends RuntimeException {
private Integer code= 300;
private String msg= "操作失败!";
public ParamsException( Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public ParamsException(Integer code) {
super("操作失败");
this.code = code;
}
public ParamsException( String msg) {
super(msg);
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;
}
}
4. 使用示例
@RequestMapping("update")
@CheckNull({"id","name"}) // 当然支持多个参数
public ResultInfo update (User user){
userService.update(user);
return Result.success();
}