首先需要引入Aop依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
创建注解接口
创建实现类
package com.lion.annontion.myAnnontion;
import com.lion.annontion.myAnnontion.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Author Lionel
* @Version V1.02021/06/24
**/
@Component
@Aspect
public class InitParamasAspect {
/**
* 初始化接口 @annotation(接口类所在位置)
*/
@Pointcut("@annotation(com.lion.annontion.myAnnontion.InitParamas)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void beforePointcut(JoinPoint joinPoint) {
System.out.println("进来了beforePointcut");
// 此处进入到方法前 可以实现一些业务逻辑
}
@Around("annotationPointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
// 获取参数名称
String[] params = methodSignature.getParameterNames();
// 获取参数值
Object[] args = joinPoint.getArgs();
if (null == params || params.length == 0){
String mes = "Using Token annotation, the token parameter is not passed, and the parameter is not valid.";
System.out.println(mes);
throw new Exception(mes);
}
User arg = (User) args[0];
// 对对应参数进行数据处理
arg.setId("!11");
arg.setName("12121");
return joinPoint.proceed();
}
/**
* 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
* @param joinPoint
*/
@AfterReturning("annotationPointcut()")
public void doAfterReturning(JoinPoint joinPoint) {
}
}