依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自定义注解作为切入点
需要的属性根据自己业务需求进行自定义:
@Target(ElementType.METHOD)//表示注解在方法上生效
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogPrintConfig {
//模块负责人
String user() default "";
//操作模块
String module() default "";
}
配置切面类
@Aspect
@Component
public class LogRecordAop {
/**
* 切入点 被这个注解所标记的方法就是被切入的点
*/
@Pointcut("@annotation(com.kevin.aopdemo.annotation.LogPrintConfig)")
public void logPointCut(){
}
//然后是大家熟悉的各个通知方法 环绕通知 前置通知 后置通知 异常通知 返回通知
@Before("logPointCut()")
public void before(JoinPoint joinPoint){
// 获取目标类名
String className = joinPoint.getTarget().getClass().getName();
// 获取方法名
String methodName = joinPoint.getSignature().getName();
System.out.println(className+"类"+methodName+"方法被访问");
// 获取参数
Object[] args = joinPoint.getArgs();
System.out.println("参数为:"+ Arrays.toString(args));
// 获取当前执行的方法
Method method = currentMethod(joinPoint, methodName);
//获取注解内容
LogPrintConfig erpLogConfig = method.getAnnotation(LogPrintConfig.class);
// 获取模块名称、负责人
String module = erpLogConfig.module();
String user = erpLogConfig.user();
System.out.println("这是前置通知");
System.out.println(module+"模块");
System.out.println(user+"为开发负责人");
//参数获取到了,具体处理根据自己的实际业务需求
}
@AfterReturning(returning = "response", pointcut = "logPointCut()")
public void doAfter(JoinPoint joinPoint, Object response) throws Exception {
//response 就是响应的返回值
System.out.println("(返回通知)返回值:"+response);
}
/**
* 异常通知, 在方法抛出异常之后执行
*/
@AfterThrowing(throwing = "ex", pointcut = "logPointCut()")
public void afterException(Exception ex) {
//可以获取到异常信息,可以统一的异常拦截
Map<String, String> exMap = new HashMap<>(1);
exMap.put("exception", ex.getMessage());
}
private Method currentMethod(JoinPoint joinPoint, String methodName) {
/**
* 获取目标类的所有方法,找到当前要执行的方法
*/
Method[] methods = joinPoint.getTarget().getClass().getMethods();
Method resultMethod = null;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
resultMethod = method;
break;
}
}
return resultMethod;
}
}
controller:
@RestController
@RequestMapping("/aop")
public class TestAopController {
@LogPrintConfig(user = "小明",module = "xx模块")
@RequestMapping("/helloWorld")
public String helloWorld(){
return "Hello world!";
}
}
demo结构
打印结果