AOP切面的一点理解
/**定义切面*/
@Aspect
/**加入spring容器*/
@Component
/**日志输出 topic对应的是log4j.properties 的属性名log4j.logger.test*/
@Slf4j(topic = "test")
/**
* @title 日志切面
* @author: chanQ
* @date: 2020/11/18 14:31
*/
public class LogAspect {
/**
* 定义切点
*/
@Pointcut("execution(* com.lovo.service..*(..))")
public void logPointcut(){}
/**
* 前置通知, 在方法执行之前执行
* @param joinPoint
*/
@Before("logPointcut()")
public void sayHello(JoinPoint joinPoint){
log.debug("前置通知"+joinPoint.getSignature());
}
/**
* 后置通知, 在方法执行之后执行,方法无论有没有异常都会执行
* @param joinPoint
*/
@After("logPointcut()")
public void sayBye(JoinPoint joinPoint){
log.debug("后置通知:"+joinPoint.getSignature());
}
/**
* 返回通知, 在方法正常结束并返回结果之后执行
* @param joinPoint
*/
@AfterReturning("logPointcut()")
public void sayReturning(JoinPoint joinPoint){
log.error("返回通知:"+joinPoint.getSignature());
}
/**
* 异常通知, 在方法抛出异常之后
* @param joinPoint
*/
@AfterThrowing("logPointcut()")
public void sayError(JoinPoint joinPoint){
log.error("异常通知:"+joinPoint.getSignature());
}
/**
* 环绕通知, 围绕着方法执行
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("execution(* com.lovo.service..*(..))")
public Object sayAround(ProceedingJoinPoint joinPoint) throws Throwable {
log.debug("环绕通知进入方法:"+joinPoint.getSignature());
Object obj = null;
try {
obj = joinPoint.proceed(joinPoint.getArgs());
} catch (Throwable throwable) {
throwable.printStackTrace();
log.error("环绕抛出异常:"+joinPoint.getSignature());
throw throwable;
}
log.debug("环绕通知退出方法:"+joinPoint.getSignature());
return obj;
}
}
执行方法后
2020-11-18 16:03:39,492 环绕通知进入方法:findAll()
2020-11-18 16:03:39,493 [前置通知List findAll()
Hibernate: select userdo0_.user_id as user_id1_0_, userdo0_.user_phone as user_pho2_0_, userdo0_.user_pwd as user_pwd3_0_ from user_info userdo0_
2020-11-18 16:03:39,650 返回通知:findAll()
2020-11-18 16:03:39,650 后置通知:findAll()
2020-11-18 16:03:39,651 环绕通知退出方法findAll()