(一)使用springAPI以及自定義類 實現AOP-aop編程


Spring的另一個重要思想是AOP,面向切面的編程,它提供了一種機制,可以在執行業務前后執行另外的代碼,Servlet中的Filter就是一種AOP思想的體現,下面通過一個例子來感受一下.

  假設我們現在需要在針對數據庫進行CRUD操作時添加一組日志,即在執行CRUD方法前后分別加上一句話,實現簡單的面向切面編程的功能.我用到的是spring4,在配置文件上較之之前的版本可能有些不同.

  使用springAPI來實現AOP,除了spring必不可少的核心jar包,還需要兩個jar包需要導入:

    1.   aspectjweaver.jar   下載鏈接: http://download.csdn.net/detail/luojiming1990/5432831
    2.   aopalliance.jar    下載鏈接:http://download.csdn.net/detail/zhaoshe/3153090

  並且配置文件的頭文件也需要略作修改,需要加入aop的命名空間(namespace),詳見下面實例中的beans.xml.

  UserService類(省略數據庫操作代碼,只做簡單的打印來模擬):

復制代碼
public class UserService {

    public void add(){
        System.out.println("添加用戶");
    }
    public void delete(){
        System.out.println("刪除用戶");
    }
    public void update(){
        System.out.println("修改用戶");
    }
    public void search(){
        System.out.println("查詢用戶");
    }
}
復制代碼

Log類(在執行增刪改查方法前執行):

復制代碼
public class Log  implements MethodBeforeAdvice{

    /***
     * method:被調用的方法對象
     * arg1:被調用的方法的參數
     * target:被調用方法的目標對象 
     */
    @Override
    public void before(Method method, Object[] arg1, Object target)
            throws Throwable {
        System.out.println(target.getClass().getName()+"中的"+method.getName()+"方法被執行");
    }

}
復制代碼

AfterLog類(在執行增刪改查方法后執行):

復制代碼
public class AfterLog implements AfterReturningAdvice{
    /**
     * returnValue:返回值類型
     * method:被調用的方法對象
     * arg1:被調用的方法的參數
     * target:被調用方法的目標對象 
     */
    @Override
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        
        System.out.println(target.getClass().getName()+"中的"+method.getName()+"方法被執行成功,返回值是"+returnValue);
        
 }
復制代碼

spring配置文件(beans.xml):

復制代碼
<?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">
    <bean id="userService" class="com.wang.service.UserService"></bean>
    <bean id="log" class="com.wang.log.Log"></bean>
    <bean id="afterlog" class="com.wang.log.AfterLog"></bean>
    <aop:config>
    <!--"*"為通配符表示所有方法,第一個* 表示任意返回值 第二個*表示所有方法      
        ".."表示任意個數的參數 -->
        <aop:pointcut expression="execution(* com.wang.service.UserService.*())" id="pointcut"/>
           <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
           <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>
復制代碼

測試代碼testDemo:

復制代碼
   @Test
    public void test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=(UserService)context.getBean("userService");
        userService.add();
        userService.search();
    }
復制代碼

運行測試可以看到控制台的打印結果:

com.wang.service.UserService中的add方法被執行
添加用戶
com.wang.service.UserService中的add方法被執行成功,返回值是null

com.wang.service.UserService中的search方法被執行
查詢用戶
com.wang.service.UserService中的search方法被執行成功,返回值是null

在配置文件中,我們看到了一些這樣的代碼:

復制代碼
 <aop:config>
    <!--"*"為通配符表示所有方法      
        ".."表示任意個數的參數 -->
        <aop:pointcut expression="execution(* com.wang.service.UserService.*())" id="pointcut"/>
           <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
           <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>
    </aop:config>
復制代碼

我們來介紹幾個AOP的相關概念,這個就比較好理解了:

  • 切面(Aspect):在本例中.add(),delete(),等方法中都有一些代碼,在真實的程序中這里不會只是簡單的打印語句而是一些有意義的代碼,這些代碼可以看做是AOP的切面.
  • 通知(Advisor):本例中的兩個日志類,這里可以成為攔截器,都是實現了某個*Advisor接口,這兩個類就是指AOP中的通知,一旦Spring符合了條件,就會發出通知,與生活中我們所說的通知不同的是,Spring中的通知是帶有執行代碼的,能實現某種功能.
  • 切入點(pointcut):在配置攔截器(<aop-config>)的時候,xml中配置了UserService中所有的方法都是用攔截器,這個配置是通過spring中的一個已經寫好的類完成的,這個類能配置對哪些方法使用攔截器,從那個地方"切入"進去.配置是可以使用通配符.

簡而言之:"切入點"負責往"什么地方"插入代碼,"通知"負責插入"什么代碼".

 

  SpringAOP將公共的業務(如日志,安全)和領域業務結合,當執行領域業務時候把公共業務加進來,實現公共業務的重復利用,使得領域業務功能更加純粹,程序員可以專注於領域業務.

  當然除了使用springAPI,我們也可以通過自定義的類,即不需要實現任何借口或繼承任何類,的方式來實現上述功能:

  只需要一個Log類:

復制代碼
public class Log  {

    public void before(){
        System.out.println("執行方法前");
    }
    
    public void after(){
        System.out.println("執行方法后");
    }
}
復制代碼

修改配置文件beans.xml中的<aop-config>為:

復制代碼
    <aop:config>
           <aop:aspect ref="log">
           <aop:pointcut expression="execution(* com.wang.service.UserService.*(..))" id="pointcut"/>
               <aop:before method="before" pointcut-ref="pointcut"/>
               <aop:after method="after" pointcut-ref="pointcut"/>
           </aop:aspect>
       </aop:config>
復制代碼

執行上面的測試代碼,打印出的結果是:

執行方法前
添加用戶
執行方法后
執行方法前
查詢用戶
執行方法后

 其實這種配置方式還可以用注解來完成,下面介紹一下使用注解的方式,順帶講一個環繞方法,它和before和after一樣,不過是在某一個方法前后都會執行的代碼:

  Log類:

復制代碼
@Aspect
public class Log  {
    @Before("execution(* com.wang.service.*.*(..))")
    public void before(){
        System.out.println("執行方法前");
    }
    @After("execution(* com.wang.service.*.*(..))")
    public void after(){
        System.out.println("執行方法后");
    }
    
    @Around("execution(* com.wang.service.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("環繞前");
        System.out.println("簽名:"+pjp.getSignature());
        //執行目標方法
        Object proceed = pjp.proceed();
        System.out.println("環繞后");
        return proceed;
    }
復制代碼

在beans.xml中,只需要將<aop-config>修改為一行代碼:

復制代碼
<?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">
    <bean id="userService" class="com.wang.service.UserService"></bean>
    <bean id="log" class="com.wang.log.Log"></bean>
    <aop:aspectj-autoproxy/>
</beans>
復制代碼

打印結果如下,讀者自行理解,這里對於around不再解釋:

環繞前
簽名:void com.wang.service.UserService.add()
執行方法前
添加用戶
環繞后
執行方法后

如果希望在before和after方法中得到當前執行方法的方法名或者參數的話,可以在bofore或者after方法中加一個參數,就是上面around方法中的參數,

  獲得方法名:String methodName=pjp.getSignature().getName();

  獲得方法參數列表:List<Object> list=Arrays.toList(pjp.getArgs());

Spring支持5種類型的通知注解:

  @Before:前置通知,在方法執行前執行

  @After:后置通知,在方法執行后執行(此注解標注的方法無法得到方法的返回值)

  @AfterRunning:返回通知,在方法返回結果之后執行(此注解標注的方法,可以獲取到方法的返回值)

  @AfterThrowing:異常通知,在方法拋出異常后執行

  @Around:環繞通知,問繞着方法執行(環繞通知必須要有ProceedingJoinPoint類型的參數,且必須要有返回值,見上面).

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM