- 前置通知。
- 后置通知,出现异常也执行。
- 返回通知,出现异常不执行。
- 异常通知。
- 环绕通知。
配置bean的方式举例子: 只写切面日志类,前置 + 后置通知。
需要两个注解:
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
/**
* 在 ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
*/
@Before("execution(* demo.aop.ArithmeticCalculator.*(..))")
private void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("the method: " + methodName + " begins width: " + Arrays.asList(args));
}
@After("execution(* demo.aop.ArithmeticCalculator.*(..))")
private void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("the method: " + methodName + " ends.");
}
}
重用切入点表达式:
@Aspect
@Component
public class LoggingAspect {
/**
* 定义一个方法,用于声明切入点表达式,一般的,该方法中不需要添加其它代码
*/
@Pointcut("execution(* demo.aop.ArithmeticCalculator.*(..))")
public void pointCutExpression() {
}
/**
* 在 ArithmeticCalculator 接口的每一个实现类的每一个方法开始之前执行一段代码
*/
@Before("pointCutExpression()")
private void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("the method: " + methodName + " begins width: " + Arrays.asList(args));
}
@After("pointCutExpression()")
private void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("the method: " + methodName + " ends.");
}
}