AspectJ AOP學習基礎

來源:互聯網
上載者:User

標籤:

一、切入點運算式

  1、execution:匹配方法的執行

    格式:execution(修飾符 傳回值類型 包.類.方法(參數) throw 異常)

      1.1修飾符,表示方法的修飾符,一般省略。

      1.2傳回型別 String表示返回String;void表示沒有傳回值;*表示返回任意類型,包括無傳回值。

      1.3包

        hjp.spring.service 表示指定的包

        hjp.spring.*.service 表示spring下子模組包含service的包

        hjp.spring.service.. 表示service目錄及其子目錄

        綜合:hjp.spring.*.service..

      1.4類 UserService表示指定的類;*Service表示以Service結尾;Test*表示以Test開頭;*表示任意類名。

      1.5方法(與類相似)

        addUser表示指定方法;add*表示以add開頭;*Do表示以Do結尾;*表示任意。

      1.6參數 ()表示沒有參數;(int)表示一個int型別參數;(int,int)表示兩個int型別參數(如果是java.lang包下的可以省略,其他類型必須寫完全限定類名);(..)表示

          任意,包括無參。

      1.7throws 異常,一般省略。

  綜合:execution(* hjp.spring.*.service..*.*(..))

  2、within:匹配包或子包中的方法,如:within(hjp.spring.service..*)

  3、this:匹配實現介面的代理對象中的方法,如:this(hjp.spring.dao.UserDao)

  4、target:匹配實現介面的目標對象中的方法,如:target(hjp.spring.daoImpl.UserDao)

  5、args:匹配參數格式符合標準的方法,如args(int,int)

  6、bean:匹配指定的bean,如:bean("userServiceId")

二、AspectJ規定的通知類型

  1、before:前置通知(應用:各種校正),在方法執行前執行,如果通知拋出異常,阻止方法運行。

  2、afterReturning:後置通知(應用:常規資料處理),方法正常返回後執行,如果方法中拋出異常,通知無法執行;在方法執行後執行,所以才可以獲得方法的傳回值。

  3、around:環繞通知(應用:可以做任何事),方法執行前後分別執行,可以阻止方法的執行。

  4、afterThrowing:拋出異常通知(應用:封裝異常資訊),方法拋出異常後執行,如果方法沒有拋出異常,無法執行。

  5、after:最終通知(應用:清理現場),方法執行完畢後執行,無論方法是否有異常出現。

  環繞通知類似代碼塊:  

try{//前置通知(before)//手動執行目標方法//後置通知(after),可獲得傳回值}catch{//拋出異常通知(afterThrowing),可獲得具體異常資訊}finally{//最終(finally)}
環繞通知類似代碼塊

 三、程式碼範例

1、代碼結構:

2、aspectj aop不是針對介面的,所有有沒有介面不影響AOP實現,下面是UserService介面和UserServiceImpl實作類別(目標類)代碼

package hjp.springAOP.springAspectJXml;public interface UserService {    void addUser();    void updateUser();}
UserService
package hjp.springAOP.springAspectJXml;public class UserServiceImpl implements UserService {    @Override    public void addUser() {        // TODO Auto-generated method stub        System.out.println("aspectj xml add user");    }    @Override    public void updateUser() {        // TODO Auto-generated method stub        //int i=9/0;        System.out.println("aspectj xml update user");    }}
UserServiceImpl

3、切面類MyAspect代碼

package hjp.springAOP.springAspectJXml;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;public class MyAspect {    public void myBefore(JoinPoint joinPoint) {        System.out.println("前置通知:" + joinPoint.getSignature().getName());    }    public void myAfterReturning(JoinPoint joinPoint, Object ret) {        System.out.println("後置通知:方法名," + joinPoint.getSignature().getName() + ";傳回值," + ret);    }    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {        System.out.println("環繞通知前");        // 手動執行目標方法        Object object = proceedingJoinPoint.proceed();        System.out.println("環繞通知後");        return object;    }    public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {        System.out.println("目標類方法" + joinPoint.getSignature().getName() + "拋出異常:" + e.getMessage());    }    public void myAfter(JoinPoint joinPoint) {        System.out.println("最終執行通知:方法:" + joinPoint.getSignature().getName());    }}
MyAspect

4、beans.xml設定檔,記得添加aop命名空間和引用地址

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"    xsi:schemaLocation="http://www.springframework.org/schema/beans                               http://www.springframework.org/schema/beans/spring-beans.xsd                              http://www.springframework.org/schema/aop                               http://www.springframework.org/schema/aop/spring-aop.xsd">    <!-- 1、建立目標類 -->    <bean id="userServiceId" class="hjp.springAOP.springAspectJXml.UserServiceImpl"></bean>    <!-- 2、建立切面類 (通知) -->    <bean id="myAspectId" class="hjp.springAOP.springAspectJXml.MyAspect"></bean>    <!-- aop編程         如果強制使用CGLIB,則設定aop:config 屬性proxy-target-class="true"     -->    <aop:config>        <!-- aspectj 編程             ref指向切面類 -->        <aop:aspect ref="myAspectId">            <!-- 聲明切入點,確定目標類上哪些方法需被增強 -->            <aop:pointcut expression="execution(* hjp.springAOP.springAspectJXml.*.*(..))" id="myPointCut" />            <!-- 聲明通知方式 -->            <!-- 1、前置通知                 method切面類中具體方法名                 pointcut-ref指向切入點(使用pointcut,也可以在通知裡配置自己的切入點運算式)            <aop:before method="myBefore" pointcut-ref="myPointCut"/>             -->             <!-- 2、後置通知,可擷取到傳回值                   returning用於設定通知的第二個參數名稱,類型為Object(注意:此處參數名稱要與切面類後置通知方法第二個參數名稱一致)             <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret"/>              -->              <!-- 3、環繞通知                                   <aop:around method="myAround" pointcut-ref="myPointCut"/>               -->               <!-- 4、拋出異常通知(測試此通知時,將目標類中updateUser方法中int i=9/0;代碼注釋去掉)                       目標方法在拋出異常時執行,如果沒有則不執行                       throwing設定拋出異常通知的第二個參數,參數名稱和此處設定的e一致,類型Throwable                        <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>                -->                <!-- 5、最終通知,即任何情況下都會執行 -->                <aop:after method="myAfter" pointcut-ref="myPointCut"/>        </aop:aspect>    </aop:config></beans>
beans.xml

5、測試類別

package hjp.springAOP.springAspectJXml;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestApp {    @Test    public void demo1() {        String xmlPath="hjp/springAOP/springAspectJXml/beans.xml";        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);        UserService userService = (UserService)applicationContext.getBean("userServiceId");        userService.addUser();        userService.updateUser();    }}
測試類別

 

AspectJ AOP學習基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.