Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring AOP 入門與底層原理拆解

什麼是 AOP

AOP 即面向切面編程。它的核心價值在於:不改動既有程式碼,就能在原有邏輯執行前後靈活地插入新機能。

目標類

package com.hyron.tony;

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

Advice:以 Around 為例

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

        // same with MethodBeforeAdvice
        System.out.println("HijackAroundMethod : Before method hijacked!");

        try {
            // proceed to original method call
            Object result = methodInvocation.proceed();

            // same with AfterReturningAdvice
            System.out.println("HijackAroundMethod : After method hijacked!");

            return result;

        } catch (IllegalArgumentException e) {
            // same with ThrowsAdvice
            System.out
                .println("HijackAroundMethod : Throw exception hijacked!");
            throw e;
        }
    }
}

組裝切面的配置檔

<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
    <property name="name" value="Yong Mook Kim" />
    <property name="url" value="https://www.mkyong.com" />
</bean>

<bean id="hijackAroundMethodBean" class="com.mkyong.aop.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>

啟動 Sample

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

import com.mkyong.customer.services.CustomerService;

public class App {
    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "Spring-Customer.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) {
        }
    }
}

這裡實際上是用 customerServiceProxy 代理了 CustomerService 的執行。在 proxy 的配置中指定 hijackAroundMethodBean 作為方法攔截器,而攔截器內部透過 invoke 方法攔下所有的方法調用,把自己的邏輯塞進去。

AOP 的兩種實現方式

上面看到的是 Spring 的寫法,而 Spring 的 AOP 本身也是建立在其他開源技術之上的,最常見的兩種是 JDK 自帶的 Proxy 與開源的 CGLIB。

差別在於:JDK Proxy 要求 Advice 必須透過介面繼承而來,如果切入的目標是實體類,就用不上;CGLIB 則可以直接覆蓋實體類的方法。Spring 對這兩者都提供了支援。

Spring 的底層實現

Spring 在配置檔中透過 ProxyFactoryBean 完成切面的編織。當我們執行這行程式碼時:

CustomerService cust = (CustomerService) appContext
                                            .getBean("customerServiceProxy");

其實是把動態物件的生成委託給了 ProxyFactoryBean。

當配置檔中 <bean> 的 class 屬性所配置的實作類是 FactoryBean 時,getBean 方法返回的並不是 FactoryBean 本身,而是 FactoryBean#getObject() 所返回的物件,相當於 FactoryBean#getObject() 代理了 getBean() 方法。

執行順序如下:

1. ProxyFactoryBean 中的 getObject

public Object getObject() throws BeansException {
    initializeAdvisorChain();
    if (isSingleton()) {
        return getSingletonInstance();
    }
    else {
        if (this.targetName == null) {
            logger.warn("Using non-singleton proxies with singleton targets is often undesirable. "
                    + "Enable prototype proxies by setting the 'targetName' property.");
        }
        return newPrototypeInstance();
    }
}

2. ProxyFactoryBean 中的 initializeAdvisorChain

從配置檔的 advice list 中取出 interceptorNames,並逐一加入 advisorChain:

for (String name : this.interceptorNames) {
    if (logger.isTraceEnabled()) {
        logger.trace("Configuring advisor or advice '" + name + "'");
    }

    if (name.endsWith(GLOBAL_SUFFIX)) {
        if (!(this.beanFactory instanceof ListableBeanFactory)) {
            throw new AopConfigException(
                    "Can only use global advisors or interceptors with a ListableBeanFactory");
        }
        addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
                name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
    }
    // ...
Copyright © Linux教程網 All Rights Reserved