首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 靜態切入點實戰(二):JdkRegexpMethodPointcut 正則運算式配置完整範例

     編輯:Java 相關知識

範例目標

攔截 People 類別中符合特定命名規則的方法,排除特定方法,驗證前置通知觸發情況。

1. 目標類 People

public class People {
    public void speak() { System.out.println("Hello,我是People!"); }
    public void Running() { System.out.println("我在跑..."); }
    public void Loving() { System.out.println("我在和MM戀愛..."); }
    public void died() { System.out.println("完了,我死了"); }
}

2. 前置通知 LogerPeople

public class LogerPeople implements MethodBeforeAdvice {
    private static final Log log = LogFactory.getLog(LogerPeople.class);
    public void before(Method method, Object[] args, Object target) throws Throwable {
        log.info(target.getClass().getSimpleName() + "正在" + method.getName() + "!");
    }
}

3. Spring XML 配置重點

<bean id="Computer" class="aop.test.People"/>
<bean id="LogerComputer" class="aop.test.LogerPeople"/>

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

<bean id="DefaultAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
  <property name="pointcut" ref="JdkRegexpPointcut"/>
  <property name="advice" ref="LogerComputer"/>
</bean>

<bean id="JdkRegexpPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
  <property name="patterns">
    <list>
      <value>.*spea.*</value>   <!-- 匹配 speak -->
      <value>.*ing</value>      <!-- 匹配 Running、Loving -->
      <value>.*di.*</value>    <!-- 匹配 died -->
    </list>
  </property>
  <property name="excludedPattern" value=".*Run.*"/> <!-- 排除 Running -->
</bean>

4. 執行測試

People p = (People) ac.getBean("ProxyFactoryBean");
p.speak();   // 被攔截 → 輸出日誌
p.Running(); // 被 excludedPattern 排除 → 無日誌
p.Loving();  // 被攔截
p.died();    // 被攔截

5. 結果驗證

People正在speak!
People正在Loving!
People正在died!

Running() 因符合 excludedPattern=".*Run.*" 而未被攔截,驗證排除規則生效。

關鍵屬性說明

  • patterns:字串陣列,任一正則匹配即納入切入點(OR 關係)。
  • excludedPattern / excludedPatterns:匹配者從切入點移除(排除優先級高於包含)。
  • 同樣支援 classFilter 屬性限定目標類別。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved