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

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

 

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

Advices:表示一個method執行前或執行後的動做。正則表達式

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

Advisor:Advice和Pointcut組成的獨立的單元,而且可以傳給proxy factory 對象。app

 

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

CustomerService.javaurl

 
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.javacode

 
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.javaxml

 
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層中的相關業務。

相關文章
相關標籤/搜索