Spring AOP實例(Pointcut,Advisor)

在上一個Spring AOP通知的例子,一個類的整個方法被自動攔截。但在大多數情況下,可能只需要一種方式來攔截一個或兩個方法,這就是爲什麼引入'切入點'的原因。它允許你通過它的方法名來攔截方法。另外,一個「切入點」必須具有「Advisor' 相關聯。

在Spring AOP中,有三個非常專業術語- AdvicesPointcut  , Advisor,把它在非官方的方式...

  • Advice – 指示之前或方法執行後採取的行動。
  • Pointcut – 指明哪些方法應該攔截,通過方法的名稱或正則表達式模式。
  • Advisor – 分組"通知"和」切入點「成爲一個單元,並把它傳遞到代理工廠對象。

再次回顧上一個 Spring AOP通知的例子。

File : CustomerService.java

package org.1ju.customer.services;

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();
    }

}

File : applicationContext.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="org.1ju.customer.services.CustomerService">
        <property name="name" value="Yong Mook Kim" />
        <property name="url" value="https://www.1ju.org" />
    </bean>

    <bean id="hijackAroundMethodBeanAdvice" class="org.1ju.aop.HijackAroundMethod" />

    <bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">

        <property name="target" ref="customerService" />

        <property name="interceptorNames">
            <list>
                <value>hijackAroundMethodBeanAdvice</value>
            </list>
        </property>
    </bean>
</beans>

File : HijackAroundMethod.java

package org.1ju.aop;

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

public class HijackAroundMethod implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        System.out.println("Method name : "
                + methodInvocation.getMethod().getName());
        System.out.println("Method arguments : "
                + Arrays.toString(methodInvocation.getArguments()));

        System.out.println("HijackAroundMethod : Before method hijacked!");

        try {
            Object result = methodInvocation.proceed();
            System.out.println("HijackAroundMethod : Before after hijacked!");

            return result;

        } catch (IllegalArgumentException e) {

            System.out.println("HijackAroundMethod : Throw exception hijacked!");
            throw e;
        }
    }
}

執行它

package org.1ju.common;

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

import org.1ju.customer.services.CustomerService;

public class App {
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });

        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) {
        }
    }
}

輸出

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Yong Mook Kim
HijackAroundMethod : Before after hijacked!
*************************
Method name : printURL
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer website : https://www.1ju.org
HijackAroundMethod : Before after hijacked!
*************************
Method name : printThrowException
Method arguments : []
HijackAroundMethod : Before method hijacked!
HijackAroundMethod : Throw exception hijacked!

客戶服務類的全部方法被截獲。後來,我們展示如何使用「切入點」只攔截printName()方法。

切入點的例子


可以通過以下兩種方式相匹配的方法:

  1. 名稱匹配
  2. 正則表達式匹配

1.切入點 - 名稱匹配的例子


通過「切入點」和「advisor」攔截printName()方法。創建NameMatchMethodPointcut 切入點bean,並提出要在「mappedName」屬性值來攔截方法名。

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

創建 DefaultPointcutAdvisor 通知 bean,通知和切入點相關聯。

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

更換代理「interceptorNames」到「customerAdvisor」(它是「hijackAroundMethodBeanAdvice」)。

<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配置文件

<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="org.1ju.customer.services.CustomerService">
        <property name="name" value="Mason" />
        <property name="url" value="https://www.1ju.org" />
    </bean>

    <bean id="hijackAroundMethodBeanAdvice" class="org.1ju.aop.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="hijackAroundMethodBeanAdvice" />
    </bean>

</beans>

再次運行,輸出

*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Mason
HijackAroundMethod : Before after hijacked!
*************************
Customer website : https://www.1ju.org
*************************

現在,只攔截 printName()方法。

customerPointcut

Spring提供了PointcutAdvisor 類來保存工作聲明advisor和切入點到不同的bean,可以使用 NameMatchMethodPointcutAdvisor 兩者結合成一個 bean。

<bean id="customerAdvisor"
        class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">

        <property name="mappedName" value="printName" />
        <property name="advice" ref="hijackAroundMethodBeanAdvice" />

    </bean>

2.切入點 - 正則表達式的例子


也可以通過使用正則表達式匹配切入點方法的名稱  – RegexpMethodPointcutAdvisor.

<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」的方法。在實踐中,可以用它來管理DAO層,聲明「.*DAO.*」 攔截所有的DAO類來支持事務。