Spring3系列10- Spring AOP——Pointcut,Advisor攔截指定方法


Spring3系列10- Spring AOP——Pointcut,Advisor

 

  上一篇的Spring AOP Advice例子中,Class(CustomerService)中的全部method都被自動的攔截了。但是大多情況下,你只需要一個方法去攔截一兩個method。這樣就引入了Pointcut(切入點)的概念,它允許你根據method的名字去攔截指定的method。另外,一個Pointcut必須結合一個Advisor來使用。

 

在Spring AOP中,有3個常用的概念,Advices、Pointcut、Advisor,解釋如下,

Advices:表示一個method執行前或執行后的動作。

Pointcut:表示根據method的名字或者正則表達式去攔截一個method。

Advisor:Advice和Pointcut組成的獨立的單元,並且能夠傳給proxy factory 對象。

 

下邊來回顧一下上一篇例子中的代碼

CustomerService.java

package com.lei.demo.aop.advice;

public class CustomerService {

    private String name;
    private String url;
 
    public void setName(String name) {
        this.name = name;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    public void printName() {
        System.out.println("Customer name : " + this.name);
    }
 
    public void printURL() {
        System.out.println("Customer website : " + this.url);
    }
 
    public void printThrowException() {
        throw new IllegalArgumentException();
    }

}

 

 配置文件Spring-AOP-Advice.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
    
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>hijackAroundMethodBean</value>
            </list>
        </property>
    </bean>
 
</beans>

 

HijackAroundMethod.java

package com.lei.demo.aop.advice;

import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class HijackAroundMethod implements MethodInterceptor {

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("Method name : "
                + methodInvocation.getMethod().getName());
        System.out.println("Method arguments : "
                + Arrays.toString(methodInvocation.getArguments()));
 
        // 相當於  MethodBeforeAdvice
        System.out.println("HijackAroundMethod : Before method hijacked!");
 
        try {
            // 調用原方法,即調用CustomerService中的方法
            Object result = methodInvocation.proceed();
 
            // 相當於 AfterReturningAdvice
            System.out.println("HijackAroundMethod : After method hijacked!");
 
            return result;
 
        } catch (IllegalArgumentException e) {
            // 相當於 ThrowsAdvice
            System.out.println("HijackAroundMethod : Throw exception hijacked!");
            throw e;
        }
    }

}

 

運行如下App.java

package com.lei.demo.aop.advice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "Spring-AOP-Advice.xml" });

        
        System.out.println("使用Spring AOP 如下");
        CustomerService cust = (CustomerService) appContext.getBean("customerServiceProxy");
        System.out.println("*************************");
        cust.printName();
        System.out.println("*************************");
        cust.printURL();
        System.out.println("*************************");
        
        try {
            cust.printThrowException();
        } catch (Exception e) {
 
        }
 
    }

}

 

 運行結果:

使用Spring AOP 如下

*************************

Method name : printName

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer name : LeiOOLei

HijackAroundMethod : After method hijacked!

*************************

Method name : printURL

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer website : http://www.cnblogs.com/leiOOlei/

HijackAroundMethod : After method hijacked!

*************************

Method name : printThrowException

Method arguments : []

HijackAroundMethod : Before method hijacked!

HijackAroundMethod : Throw exception hijacked!

 

上邊的結果中,CustomerService.java中,全部的method方法全部被攔截了,下邊我們將展示怎樣利用Pointcuts只攔截printName()。

 

你可以用名字匹配法和正則表達式匹配法去匹配要攔截的method。

1.      Pointcut——Name match example

通過pointcut和advisor攔截printName()方法。

創建一個NameMatchMethodPointcut的bean,將你想攔截的方法的名字printName注入到屬性mappedName,如下

<bean id="customerPointcut"
        class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedName" value="printName" />
</bean>

 

 創建一個DefaultPointcutAdvisor的advisor bean,將pointcut和advice關聯起來。

<bean id="customerAdvisor"
        class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="pointcut" ref="customerPointcut" />
        <property name="advice" ref=" hijackAroundMethodBean " />
</bean>

 

更改代理的interceptorNames值,將上邊的advisor( customerAdvisor)替代原來的hijackAroundMethodBean。

<bean id="customerServiceProxy"
        class="org.springframework.aop.framework.ProxyFactoryBean">
 
        <property name="target" ref="customerService" />
 
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
</bean>

 

所有的配置文件如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
 
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
 
        <property name="target" ref="customerService" />
 
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
    </bean>
 
    <bean id="customerPointcut"class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedName" value="printName" />
    </bean>
 
    <bean id="customerAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="pointcut" ref="customerPointcut" />
        <property name="advice" ref=" hijackAroundMethodBean " />
    </bean>
 
</beans>

 

 再運行一下App.java,輸出結果如下:

使用Spring AOP 如下

*************************

Method name : printName

Method arguments : []

HijackAroundMethod : Before method hijacked!

Customer name : LeiOOLei

HijackAroundMethod : After method hijacked!

*************************

Customer website : http://www.cnblogs.com/leiOOlei/

*************************

 

以上運行結果顯示,只攔截了printName()方法。

 

注意:

以上配置中pointcut和advisor可以合並在一起配置,即不用單獨配置customerPointcutcustomerAdvisor,只要配置customerAdvisor時class選擇NameMatchMethodPointcutAdvisor如下:

<bean id="customerAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="hijackAroundMethodBean" />
</bean>

 

這樣,整個配置文件如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="customerService" class="com.lei.demo.aop.advice.CustomerService">
        <property name="name" value="LeiOOLei" />
        <property name="url" value="http://www.cnblogs.com/leiOOlei/" />
    </bean>
    
    <bean id="hijackAroundMethodBean" class="com.lei.demo.aop.advice.HijackAroundMethod" />
 
    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
    </bean>
    
    
    <bean id="customerAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
        <property name="mappedName" value="printName" />
        <property name="advice" ref="hijackAroundMethodBean" />
    </bean>
 
</beans>

 

  實際上這種做法將method名字與具體的advice捆綁在一起,有悖於Spring松耦合理念,如果將method名字單獨配置成pointcut(切入點),advice和pointcut的結合會更靈活,使一個pointcut可以和多個advice結合。

2.      Pointcut——Regular exxpression match example

你可以配置用正則表達式匹配需要攔截的method,如下配置

<bean id="customerAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <property name="patterns">
            <list>
                <value>.*URL.*</value>
            </list>
        </property>
        <property name="advice" ref="hijackAroundMethodBeanAdvice" />
    </bean>

 

現在,你可以攔截名字中包含URL字符的method了,在實際工作中,你可以用它來管理DAO層,例如,你可以用“.*DAO.*”來攔截所有DAO層中的相關業務。

 

 

 

 

 


免責聲明!

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



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