我的春天AOP不起作用

时间:2009-11-04 05:40:14

标签: java spring 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不起作用,但目标执行。

1 个答案:

答案 0 :(得分: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>