Spring AOP切面變成——創建增強類


說明

Spring使用增強類定義橫向邏輯,同時Spring只支持方法連接點,增量類還包含在方法的哪一點添加橫切代碼的方位信息。所以增強既包含橫向邏輯,又包含部分連接點的信息。

類型

按着增強在目標類方法的連接點位置,分為

  1. 前置增強
  2. 后置增強
  3. 環繞增強
  4. 異常拋出增強
  5. 引介增強

前置增強

場景:服務生提供2中服務:歡迎顧客、服務顧客

package com.jihite;

public interface Waiter {
    void greetTo(String name);
    void serveTo(String name);
}

新來的服務生情況如下

package com.jihite;

public class NaiveWaiter implements Waiter{
    @Override
    public void greetTo(String name) {
        System.out.println("Greet to " + name);
    }

    @Override
    public void serveTo(String name) {
        System.out.println("Serve to " + name);
    }
}

新來的服務生上來就提供服務,比較生猛,在做每件事之前都改打個招呼,下面定義前置增強類

package com.jihite;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class GreetingBeforeAdvice implements MethodBeforeAdvice{
    @Override
    public void before(Method method, Object[] args, Object obj) throws Throwable {
        String clientName = (String)args[0];
        System.out.println("How are you! Mr." + clientName);
    }
}

在Spring中配置

在src/main/resources中定義beans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="greetingBeforeAdvice" class="com.jihite.GreetingBeforeAdvice"/>
    <bean id="targetBefore" class="com.jihite.NaiveWaiter"/>
    <bean id="waiterBefore" class="org.springframework.aop.framework.ProxyFactoryBean"
          p:interceptorNames="greetingBeforeAdvice"
          p:target-ref="targetBefore"
          p:proxyTargetClass="true"
          />
</beans>

測試

public class BeforeAdviceTest {
    private Waiter target;
    private BeforeAdvice advice;
    private ProxyFactory pf;

    @BeforeTest
    public void init() {
        target = new NaiveWaiter();
        advice = new GreetingBeforeAdvice();
        pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvice(advice);
    }
}

結果

How are you! Mr.Jphn
Greet to Jphn
How are you! Mr.Tom
Serve to Tom

其他類型的增強類與前置增強類似,可參考代碼

代碼

鏈接


免責聲明!

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



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