Spring除了支持Schema方式配置AOP,还支持注解方式:使用@Aspect来配置
(1) Spring默认不支持@Aspect的切面声明,必须在applicationContext.xml文件中如下配置
开启@Aspect支持:
- <aop:aspectj-autoproxy/>
(2)通过以上配置,Spring就能发现用@Aspect注解的切面内并把它应用到目标对象上。
- @Override
public void add() {
// TODO Auto-generated method stub
System.out.println("add Student");
int i=10/0; //运行时发生的异常
}
(3)定义一个切面:
- @Aspect
public class Transactions {
// 前置通知(Before advice):在某连接点之前执行的通知,但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。
@Before("execution(* com.hlx.tx.aspect.*.*(..))")
public void beginTransaction(JoinPoint jp) {
// System.out.println(jp.getSignature().getName());
System.out.println("前置通知-->开始事务!");
}
// 后置通知(After returning advice):在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
@AfterReturning(pointcut="execution(* com.hlx.tx.aspect.*.*(..))",returning="obj" )
public void commitTransaction(JoinPoint jp, Object obj) {
List<Student> list = (List<Student>) obj;
// System.out.println("学生的个数:"+list.size());
System.out.println("后置通知-->结束事务!");
}
// 异常通知(After throwing advice):在方法抛出异常退出时执行的通知。
@org.aspectj.lang.annotation.AfterThrowing(pointcut="execution(* com.hlx.tx.aspect.*.*(..))",throwing="ex")
public void AfterThrowing(Throwable ex) {
System.out.println("异常通知!" + ex.toString());
}
// 最终通知(After (finally) advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。
@After("execution(* com.hlx.tx.aspect.*.*(..))")
public void afterAdvice() {
System.out.println("不管有没有异常都执行! 最终通知");
}
// 环绕通知(Around Advice):包围一个连接点的通知,如方法调用。这是最强大的一种通知类型。
//环绕通知在一个方法执行之前和之后执行
@Around("execution(* com.hlx.tx.aspect.*.*(..))")
public void aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
String method = pjp.getSignature().getName();
// 判断(控制执行目标方法)
// if (method.equals("add")) {
System.out.println("环绕通知");
pjp.proceed();
//}
}
}
(4)显示结果:
- 环绕通知
前置通知-->开始事务!
add Student
不管有没有异常都执行! 最终通知
异常通知!java.lang.ArithmeticException: / by zero