使用註解方式配置Spring中的面向切面編程AOP

<code>package com.huanfeng.ssm.controller;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

//@Aspect表示這是一個通知類
@Aspect
public class MyAdvice {
	    //前置通知
	    @Before("execution(* com.huanfeng.service.*ServiceImpl.*(..))")
		public void before(){
			System.out.println("這是前置通知!!");
		}
		//後置通知
	    @AfterReturning("execution(* com.huanfeng.service.*ServiceImpl.*(..))")
		public void afterReturning(){
			System.out.println("這是後置通知(如果出現異常不會調用)!!");
		}
		//環繞通知
	    @Around("execution(* com.huanfeng.service.*ServiceImpl.*(..))")
		public Object around(ProceedingJoinPoint pjp) throws Throwable {
			System.out.println("這是環繞通知之前的部分!!");
			Object proceed = pjp.proceed();//調用目標方法
			System.out.println("這是環繞通知之後的部分!!");
			return proceed;
		}
		//異常通知
	    @AfterThrowing("execution(* com.huanfeng.service.*ServiceImpl.*(..))")
		public void afterException(){
			System.out.println("出事啦!出現異常了!!");
		}
		//後置通知
	    @After("execution(* com.huanfeng.service.*ServiceImpl.*(..))")
		public void after(){
			System.out.println("這是後置通知(出現異常也會調用)!!");
		}
}/<code>


分享到:


相關文章: