SpringAOP中的注解配置詳解
這篇文章主要介紹了SpringAOP中的注解配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
使用注解實現(xiàn)SpringAOP的功能:
例子:
//表示這是被注入Spring容器中的
@Component
//表示這是個切面類
@Aspect
public class AnnotationHandler {
/*
* 在一個方法上面加上注解來定義切入點
* 這個切入點的名字就是這個方法的名字
* 這個方法本身不需要有什么作用
* 這個方法的意義就是:給這個 @Pointcut注解一個可以書寫的地方
* 因為注解只能寫在方法、屬性、類的上面,并且方法名作為切入點的名字
* */
//簡單來說就是將查到的方法用myPointCut()方法名代替
@Pointcut("execution(public * com.briup.aop.service..*.*(..))")
public void myPointCut(){
}
//注:這里面的所有方法的JoinPoint類型參數(shù)都可以去掉不寫,如果確實用不上的話
@Before("myPointCut()")//在myPointCut()中查到的方法之前切入
public void beforeTest(JoinPoint p){
System.out.println(p.getSignature().getName()+" before...");
}
/*
* @After和@AfterReturning
*
* @After標(biāo)注的方法會在切入點上的方法結(jié)束后被調(diào)用(不管是不是正常的結(jié)束).
* @AfterReturning標(biāo)注的方法只會在切入點上的方法正常結(jié)束后才被調(diào)用.
* */
@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()中查到的方法環(huán)繞切入
public Object aroundTest(ProceedingJoinPoint pjp)throws Throwable{
System.out.println(pjp.getSignature().getName()+" is start..");
//調(diào)用連接點的方法去執(zhí)行
Object obj = pjp.proceed();
System.out.println(pjp.getSignature().getName()+" is end..");
return obj;
}
//在切入點中的方法執(zhí)行期間拋出異常的時候,會調(diào)用這個 @AfterThrowing注解所標(biāo)注的方法
@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進行代理
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java線程監(jiān)聽,意外退出線程后自動重啟的實現(xiàn)方法
下面小編就為大家?guī)硪黄狫ava線程監(jiān)聽,意外退出線程后自動重啟的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
自定義JmsListenerContainerFactory時,containerFactory字段解讀
這篇文章主要介紹了自定義JmsListenerContainerFactory時,containerFactory字段解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Java實現(xiàn)前端jsencrypt.js加密后端解密的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用jsencrypt.js實現(xiàn)前端加密,利用Java實現(xiàn)后端解密的功能,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-09-09
SpringBoot條件注解@Conditional詳細(xì)解析
這篇文章主要介紹了SpringBoot條件注解@Conditional詳細(xì)解析,@Conditional是Spring4.0提供的一個用于條件裝配的注解,其定義了一個Condition的數(shù)組,只有當(dāng)數(shù)組所有的條件都滿足的時候,組件才會被導(dǎo)入容器,需要的朋友可以參考下2023-11-11

