【问题标题】:My Spring AOP not working我的 Spring AOP 不工作
【发布时间】:2009-11-04 17:59:25
【问题描述】:

我需要帮助使 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 不起作用,但目标执行。

【问题讨论】:

    标签: java spring aop


    【解决方案1】:

    您已经声明了目标 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>
    

    【讨论】:

    • (我还应该说,这是一个奇怪的 bean,因为您不需要查找它或将其连接到任何其他 bean。当您启动容器时,bean 会启动并将通知添加到所有匹配的 bean 名称)。只需将其添加到您的 XML 中,只要您以工具包描述的方式访问您的 bean,它就可以工作。
    • 这成功了!但一直以来,我都认为是受众顾问应用了建议,因为它有建议(建议属性)并且知道何时应用它(模式属性)。
    • Advisor 中的模式属性描述了要应用的方法,而不是要应用的 bean。我觉得这让我自己感到困惑——我强烈建议您研究 aop: 命名空间,这允许您以更直观的方式进行配置。另外,请查看 AspectJ 切入点语法。参考手册中描述了这两个主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多