基于注解方式实现
@Before前置通知
在目标方法(切入点)执行之前执行。
可以统一修改参数,例如:项目已完成,需要把一些明文字段加密为密文存储;
1、pom引入需要的依赖
<!-- 切面-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- hutool工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.13</version>
</dependency>
2、传参VO
public class UserVO {
private Double salary;
// get + set 方法
}
3、自定义个注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyEncryption {
// 加密字段
String field() default "";
// 表名
String table() default "";
}
4、新建切面类(Before)
@Component
@Aspect
public class MyAspect {
// // 定义一个切入点
// @Pointcut("@annotation(com.example.aop.MyEncryption)")
// public void pt(){}
// 定义一个通知
@Before("@annotation(com.example.aop.MyEncryption)")
public void deBefore(JoinPoint joinPoint) throws Throwable {
System.out.println("before...");
// 获取自定义注解@MyOperationLog
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Annotation annotation = AnnotationUtil.getAnnotation(method, MyEncryption.class);
String field = (String) annotation.getClass().getMethod("field").invoke(annotation);
String table = (String) annotation.getClass().getMethod("table").invoke(annotation);
Object[] args = joinPoint.getArgs();
for (Object arg:args){
String s = BeanUtil.getFieldValue(arg, field).toString();
String methodName2 = "11111"+s;
BeanUtil.setFieldValue(arg,field,methodName2);
}
}
}
5、在需要执行切面的方法加注解
@Service
public class TestServiceImpl implements TestService {
@Override
@MyEncryption(field="salary")
public String query(UserVO a) {
return a.toString();
}
}
@AfterReturning后置通知
在目标方法(切入点)返回结果之后执行,可用于统一解密
1、编写注解类
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyDecryption {
// 加密字段
String field() default "";
// 表名
String table() default "";
}
2、编写切面方法
@Component
@Aspect
public class MyAspect {
@AfterReturning(pointcut = "@annotation(com.example.aop.MyDecryption)",returning = "result")
public void doAfter(JoinPoint joinPoint,Object result) throws Throwable {
System.out.println("执行后。。。。。。");
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Annotation decryptAopAnno = AnnotationUtil.getAnnotation(method, MyDecryption.class);
//获取参数
String field = (String) decryptAopAnno.getClass().getMethod("field").invoke(decryptAopAnno);
String table = (String) decryptAopAnno.getClass().getMethod("table").invoke(decryptAopAnno);
}
}
3、在需要执行切面的方法加注解
@Override
@MyDecryption(field="salary",table="t_user")
public String result() {
System.out.println("执行。。。");
return "0123";
}