需要引入的依赖maven pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.19</version>
</dependency>
package.annotation
class.CheckBean
import java.lang.annotation.*;
@Repeatable(value = CheckBeans.class)
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckBean {
String[] value() default "";
String bean() default "";
String[] fields() default "";
}
class.CheckBeans
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckBeans {
CheckBean[] value();
}
package.aop
class.CheckAop
import com.zan.rwj.system.annotation.CheckBean;
import com.zan.rwj.system.annotation.CheckBeans;
import com.zan.rwj.system.exception.CheckAOPException;
import com.zan.rwj.system.utils.CheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.stream.Collectors;
@Aspect
@Component
@Slf4j
public class CheckAop {
static {
log.info("Check Service Starting");
}
@Pointcut("execution(* *(..))")
private void pointCut() {}
@Before("pointCut() && @annotation(checkBean)")
public boolean beforeCheckBean(JoinPoint point, CheckBean checkBean){
boolean flag = true;
Object[] args = point.getArgs();
MethodSignature signature = (MethodSignature) point.getSignature();
if (checkBean.bean().equals("")){
for (Object arg : args) {
flag = getFlag(signature.getParameterNames()[0],checkBean.fields(),arg);
}
}else {
int index = Arrays.stream(signature.getParameterNames()).collect(Collectors.toList()).indexOf(checkBean.bean());
if (index==-1) throw new CheckAOPException("Can't find this bean: " + checkBean.bean());
flag = getFlag(checkBean.bean(), checkBean.fields(), args[index]);
}
return flag;
}
@Before("pointCut() && @annotation(checkBeans)")
public boolean beforeCheckBeans(JoinPoint point, CheckBeans checkBeans){
Object[] args = point.getArgs();
boolean flag = true;
if (checkBeans.value().length>args.length) throw new CheckAOPException("The number of annotations does not match the number of parameters");
MethodSignature signature = (MethodSignature) point.getSignature();
for (int i = 0; i < checkBeans.value().length; i++) {
if (checkBeans.value()[i].bean().equals("")){
flag = getFlag(signature.getParameterNames()[i],checkBeans.value()[i].fields(),args[i]);
}else {
int index = Arrays.stream(signature.getParameterNames()).collect(Collectors.toList()).indexOf(checkBeans.value()[i].bean());
if (index==-1) throw new CheckAOPException("Can't find this bean: " + checkBeans.value()[i].bean());
flag = getFlag(checkBeans.value()[i].bean(),checkBeans.value()[i].fields(),args[index]);
}
}
return flag;
}
private boolean getFlag(String beanName,String[] fields,Object o){
try {
return fields[0].equals("")?CheckUtils.checkNull(o):CheckUtils.checkNull(o,fields);
}catch (Exception e){
throw new CheckAOPException(e.getMessage() + " in param ["+beanName+"]");
}
}
}
package.exception
class.CheckAopException
public class CheckAOPException extends RuntimeException{
public static final String CHECK_AOP_EXCEPTION = "CheckAopException";
public CheckAOPException(String message) {
super("["+CHECK_AOP_EXCEPTION+"]-"+message);
}
}
class.CheckParamIsNull
public class CheckParamIsNull extends RuntimeException{
public CheckParamIsNull(String e) {
super(e);
}
}
class.ValueNullExcetion
public class ValueNullException extends RuntimeException{
public ValueNullException(String e) {
super(e);
}
public ValueNullException(Class<?> c,String name) {
super("["+c+"."+name+"] this value can't be null");
}
}
package.utils
class.CheckUtils
import com.zan.rwj.system.exception.CheckParamIsNull;
import com.zan.rwj.system.exception.ValueNullException;
import java.lang.reflect.Field;
public class CheckUtils {
/**
* Determines whether all properties in this object are empty,throw an exception if there is a null value
* 判断此对象中的所有属性是否为空,如果存在空值,则抛出异常
*
* @param o The object that needs to be judged
* @return Property values are not empty and return true
*/
public static boolean checkNull(Object o) {
if (o == null) throw new CheckParamIsNull("this method param <Object> can't be null ");
Class<?> c = o.getClass();
Field[] declaredFields = c.getDeclaredFields();
for (Field f : declaredFields) {
f.setAccessible(true);
try {
if (f.get(o) == null || f.get(o).equals("")) throw new ValueNullException(" "+c+"'s "+f.getName()+" this value can't be null");
} catch (IllegalAccessException e) {
throw new RuntimeException("IllegalAccessException");
}
}
return true;
}
/**
* Determines whether all properties in this object are empty,return false if there is a null value
* 判断此对象中的所有属性是否为空,如果存在空值,则返回false,否则返回true
*
* @param o The object that needs to be judged
* @return Property values are not empty and return true, otherwise return false
*/
public static boolean checkNullWithout(Object o) {
if (o == null) return false;
Class<?> c = o.getClass();
Field[] declaredFields = c.getDeclaredFields();
for (Field f : declaredFields) {
f.setAccessible(true);
try {
if (f.get(o) == null || f.get(o).equals("")) return false;
} catch (IllegalAccessException e) {
throw new RuntimeException("IllegalAccessException");
}
}
return true;
}
/**
* Judge whether the attribute with the attribute name in fields in this object is null. If there is a null value, throw an exception
* 判断此对象中属性名在fields中的属性是否为空,如果存在空值,则抛出异常
*
* @param o The object that needs to be judged
* @param fields The names of the attribute to be determined
* @return Property values are not empty and return true
*/
public static boolean checkNull(Object o, String... fields) {
if (o == null) throw new CheckParamIsNull("this method param <Object> can't be null ");
Class<?> c = o.getClass();
for (String field : fields) {
Field f;
try {
f = c.getDeclaredField(field);
} catch (NoSuchFieldException e) {
throw new RuntimeException("["+field+"] No Such Field Exception");
}
f.setAccessible(true);
try {
if (f.get(o) == null || f.get(o).equals("")) throw new ValueNullException(" "+c+"'s "+f.getName()+" this value can't be null");
} catch (IllegalAccessException e) {
throw new RuntimeException("IllegalAccessException");
}
}
return true;
}
/**
* Judge whether the attribute with the attribute name in fields in this object is null. If there is a null value, return false
* 判断此对象中属性名在fields中的属性是否为空,如果存在空值,返回false
*
* @param o The object that needs to be judged
* @param fields The names of the attribute to be determined
* @return Property values are not empty and return true, otherwise return false
*/
public static boolean checkNullWithout(Object o, String... fields) {
if (o == null) return false;
Class<?> c = o.getClass();
for (String field : fields) {
Field f;
try {
f = c.getDeclaredField(field);
} catch (NoSuchFieldException e) {
throw new RuntimeException("No Such Field Exception");
}
f.setAccessible(true);
try {
if (f.get(o) == null || f.get(o).equals("")) return false;
} catch (IllegalAccessException e) {
throw new RuntimeException("IllegalAccessException");
}
}
return true;
}
/**
* Directly pass in the parameter and judge whether it is null (throw exception)
* 直接将参数传递进来,并判断其是否为空值
*
* @param params Parameters to be judged
* @return Parameters values are not empty and return true, otherwise throw an exception
*/
public static boolean checkNullOfValue(Object... params) {
for (Object o : params) {
if (o == null || o.equals(""))throw new ValueNullException("There is a value of null");
}
return true;
}
/**
* Directly pass in the parameter and judge whether it is null
* 直接将参数传递进来,并判断其是否为空值
*
* @param params Parameters to be judged
* @return Parameters values are not empty and return true, otherwise return false
*/
public static boolean checkNullOfValueWithout(Object... params) {
for (Object o : params) {
if (o == null || o.equals(""))return false;
}
return true;
}
public static boolean checkValue(Object o,String[] params,String[] value){
if (params.length!=value.length)throw new ValueNullException(o.getClass(),params[0]);
return true;
}
}
使用示例:
@CheckBean(bean = "role",fields = {"name","age"})//bean对应的是入参实体类名,fields对应的是bean中的属性
@PostMapping("findAll")
public List<SysRole> findAll(@RequestBody SysRole role){
List<SysRole> list = sysRoleService.findAll();
return list;
}