SqlParamCheck
package com.example.aopproject.annotation;
import java.lang.annotation.*;
/**
* @author Bin
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SqlParamCheck {
String[] tableType() default {};
String[] filedType() default {};
}
AopAdvice
package com.example.aopproject.aop;
import com.example.aopproject.annotation.SqlParamCheck;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Bin
*/
@Aspect
@Component
@Slf4j
public class AopAdvice {
@Pointcut("@annotation(com.example.aopproject.annotation.SqlParamCheck)")
public void test() {
}
public static final List<String> TABLE = Arrays.asList("lisi");
public static final List<String> FILED = Arrays.asList("select", "from", "where");
@Around("test()")
public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
// 获取参数名称
List<Parameter> parameters = Arrays.stream(signature.getMethod().getParameters()).collect(Collectors.toList());
for (Parameter parameter : parameters) {
String name = parameter.getName();
log.info("参数名:" + name);
}
// 获取自定义注解的值
SqlParamCheck customAnnotation = signature.getMethod().getAnnotation(SqlParamCheck.class);
String[] filedTypes = customAnnotation.filedType();
String[] tableTypes = customAnnotation.tableType();
System.out.println("注解表类型:" + Arrays.toString(filedTypes));
System.out.println("注解字段类型:" + Arrays.toString(tableTypes));
// 获取参数值
List<Object> args = Arrays.stream(proceedingJoinPoint.getArgs()).collect(Collectors.toList());
System.out.println("所有参数数据:" + args);
try {
return proceedingJoinPoint.proceed();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}