轉自: http://zywang.iteye.com/blog/974226
使用@AspectJ標簽
- 在配置文件中添加 <aop:aspectj-autoproxy/> 注解
- 創建一個Java文件,使用@Aspect注解修飾該類
- 創建一個方法,使用@Before、@After、@Around等進行修飾,在注解中寫上切入點的表達式
說明:上述Java文件創建好后,需要將其在Spring的容器中進行聲明,可以在配置文件中定義<bean/>節點,也可以使用@Component組件進行修飾
示例:
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.After;
- import org.aspectj.lang.annotation.AfterThrowing;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.springframework.stereotype.Component;
- /**
- *基于注解的AOP日志示例
- *@authorZYWANG2011-3-24
- */
- @Component
- @Aspect
- public class AopLog{
- //方法執行前調用
- @Before ( "execution(*com.zywang.services.impl.*.*(..))" )
- public void before(){
- System.out.println( "before" );
- }
- //方法執行后調用
- @After ( "execution(*com.zywang.services.impl.*.*(..))" )
- public void after(){
- System.out.println( "after" );
- }
- //方法執行的前后調用
- @Around ( "execution(*com.zywang.services.impl.*.*(..))" )
- public Objectaround(ProceedingJoinPointpoint) throws Throwable{
- System.out.println( "beginaround" );
- Objectobject=point.proceed();
- System.out.println( "endaround" );
- return object;
- }
- //方法運行出現異常時調用
- @AfterThrowing (pointcut= "execution(*com.zywang.services.impl.*.*(..))" ,throwing= "ex" )
- public void afterThrowing(Exceptionex){
- System.out.println( "afterThrowing" );
- System.out.println(ex);
- }
- }
上面這段代碼中多次使用了重復的切入點,這種情況下,可以使用@Pointcut標注,來修改一個切入點方法(這個方法不需要參數和方法體),然后就可以在@Before等標注中引用該方法作為切入點,示例如下:
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.stereotype.Component;
- /**
- *基于注解的AOP日志示例
- *@authorZYWANG2011-3-24
- */
- @Component
- @Aspect
- public class AopLog{
- @Pointcut ( "execution(*com.iflysse.school.services.impl.*.*(..))" )
- public void pointcut(){}
- //方法執行前調用
- @Before ( "pointcut()" )
- public void before(){
- System.out.println( "before" );
- }
- //方法執行的前后調用
- @Around ( "pointcut()" )
- public Objectaround(ProceedingJoinPointpoint) throws Throwable{
- System.out.println( "beginaround" );
- Objectobject=point.proceed();
- System.out.println( "endaround" );
- return object;
- }
- }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
