1. 程式人生 > 程式設計 >SpringAOP中的註解配置詳解

SpringAOP中的註解配置詳解

這篇文章主要介紹了SpringAOP中的註解配置詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

使用註解實現SpringAOP的功能:

例子:

//表示這是被注入Spring容器中的
@Component
//表示這是個切面類
@Aspect
public class AnnotationHandler {
	/*
* 在一個方法上面加上註解來定義切入點
* 這個切入點的名字就是這個方法的名字
* 這個方法本身不需要有什麼作用
* 這個方法的意義就是:給這個 @Pointcut註解一個可以書寫的地方
* 因為註解只能寫在方法、屬性、類的上面,並且方法名作為切入點的名字
* */
	//簡單來說就是將查到的方法用myPointCut()方法名代替
	@Pointcut("execution(public * com.briup.aop.service..*.*(..))")
	public void myPointCut(){
	}
	//注:這裡面的所有方法的JoinPoint型別引數都可以去掉不寫,如果確實用不上的話
	@Before("myPointCut()")//在myPointCut()中查到的方法之前切入
	public void beforeTest(JoinPoint p){
		System.out.println(p.getSignature().getName()+" before...");
	}
	/*
* @After和@AfterReturning
* 
* @After標註的方法會在切入點上的方法結束後被呼叫(不管是不是正常的結束).
* @AfterReturning標註的方法只會在切入點上的方法正常結束後才被呼叫.
* */
	@After("myPointCut()")//在myPointCut()中查到的方法之後切入
	public void afterTest(JoinPoint p){
		System.out.println(p.getSignature().getName()+" after...");
	}
	@AfterReturning("myPointCut()")
	public void afterReturningTest(JoinPoint p){
		System.out.println(p.getSignature().getName()+" afterReturning");
	}
	@Around("myPointCut()")//在myPointCut()中查到的方法環繞切入
	public Object aroundTest(ProceedingJoinPoint pjp)throws Throwable{
		System.out.println(pjp.getSignature().getName()+" is start..");
		//呼叫連線點的方法去執行
		Object obj = pjp.proceed();
		System.out.println(pjp.getSignature().getName()+" is end..");
		return obj;
	}
	//在切入點中的方法執行期間丟擲異常的時候,會呼叫這個 @AfterThrowing註解所標註的方法
	@AfterThrowing(value="myPointCut()",throwing="ex")
	public void throwingTest(JoinPoint p,Exception ex){
		System.out.println(p.getSignature().getName()+" is throwing..."+ex.getMessage());
	}
}

xml配置:注意給例子中使用的其他的類上面也使用註解

<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.briup.aop"/>

<!-- 讓Spring掃描註解 -->
<context:component-scan base-package="com.briup.aop"></context:component-scan>
<!-- 識別AspectJ的註解 -->
<aop:aspectj-autoproxy/>

注意:<aop:aspectj-autoproxy proxy-target-class="true"/>這樣配置則是強制使用CGLIB進行代理

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。