2009-11-04 80 views
0

我需要幫助使AOP工作。我在這裏錯過了什麼?我的彈簧AOP不工作

<?xml version="1.0" encoding="UTF-8"?> 
<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.0.xsd"> 

    <bean id="duke" class="com.tutorial.springidol.Singer"> 
     <constructor-arg value="Duke"/> 
     <constructor-arg> 
     <bean class="com.tutorial.springidol.Song"> 
      <property name="title" value="ABC"/> 
    </bean>   
     </constructor-arg> 
    </bean> 

    <bean id="audienceAdvice" class="com.tutorial.advice.AudienceAdvice"> 
    <property name="audience"> 
     <bean class="com.tutorial.springidol.Audience"/> 
    </property> 
    </bean> 

    <bean id="audienceAdvisor" 
     class="org.springframework. 
     aop.support.RegexpMethodPointcutAdvisor"> 

     <property name="advice" ref="audienceAdvice"/> 
     <property name="pattern" value=".*perform"/> 
    </bean> 
</beans> 

AudienceAdvice.java

public class AudienceAdvice implements MethodBeforeAdvice, 
        AfterReturningAdvice { 
    @Override 
    public void before(Method arg0, Object[] arg1, Object arg2) 
      throws Throwable { 
     audience.takeSeats(); 
     audience.turnOffCellphones(); 
    } 

    @Override 
    public void afterReturning(Object arg0, Method arg1, Object[] arg2, 
      Object arg3) throws Throwable { 
     audience.applaud(); 
    } 
    private Audience audience; 
    public void setAudience(Audience audience) { 
     this.audience = audience; 
    } 
} 

的AOP不工作,但目標雖然執行。

回答

0

您已經聲明瞭目標bean和通知,但默認情況下,Spring並不知道實際將通知應用於目標。

您需要運行Autoproxy。 。

<!-- Autoproxy --> 
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> 
    <property name="beanNames"> 
     <list> 
      <value>duke</value>    
     </list> 
    </property> 

    <property name="interceptorNames"> 
     <list> 
      <value>audienceAdvisor</value> 
     </list> 
    </property> 
</bean> 
+0

(我還應該說,這是在一個奇怪的豆你不必看它或電線入其它bean當您啓動:要做到這一點

的一種方式容器,bean啓動並將建議添加到所有匹配的bean名稱中)。只需將它添加到您的XML中,並且只要您按照工具包描述的方式訪問您的bean,它就可以工作。 – 2009-11-04 10:01:38

+0

這工作!但是這一次我以爲這是觀衆顧問,因爲它有建議(建議屬性)並且知道何時應用它(模式屬性),所以應用了建議。 – Jeune 2009-11-04 14:52:18

+0

Advisor中的pattern屬性描述了要應用的方法,而不是要應用的bean。 我覺得這讓我感到困惑 - 我強烈建議您調查aop:命名空間,這樣可以讓您以更直觀的方式進行配置。另外,請看AspectJ切入點語法。這兩個主題在參考手冊中都有描述。 – 2009-11-04 20:40:41