【问题标题】:Spring AOP Configuration (XML)Spring AOP 配置 (XML)
【发布时间】:2011-11-26 03:33:20
【问题描述】:

我第一次尝试使用 Spring AOP 并陷入 XML 配置中。我正在尝试启动并运行基于 AOP 的“日志记录”的模拟版本,使用 MethodInterceptor 包装特定的方法调用并在这些方法调用之前和之后执行一些简单的 System.out.println 语句。简单的东西,对吧?

所以我的项目有很多类,其中两个是FizzBuzz。 Fizz 有一个名为foo() 的方法,Buzz 有一个名为wapap() 的方法。每次在运行时调用这些方法时,我希望我的 LoggingInterceptor 围绕它们执行其 invoke() 方法:

public class LoggingInterceptor implements MethodInterceptor
{
    public Object invoke(MethodInvocation methodInvocation)
    {
        try
        {
            System.out.println("About to call a special method.");
            Object result = methodInvocation.proceed();
            return result;
        }
        finally
        {
            System.out.println("Finished executing the special method.");
        }
    }
}

所以我理解了建议(我的拦截器 impl)、切入点(将围绕它们执行建议的方法)和切入点顾问(建议和切入点之间的绑定)的概念。

我只是在努力将它完全绑定到一个简单的 XML 配置中。

这是我目前所拥有的,但我知道它缺少切入点和切入点顾问定义,可能还有更多。

<beans default-autowire="no" >
    <bean name="loggingInterceptor" class="org.me.myproject.aop.LoggingInterceptor"/>   
</beans>

我在这里缺少什么来使这个特定于 Fizz::foo() 和 Buzz::wapap() 调用?

非常感谢任何朝着正确方向的推动!

【问题讨论】:

    标签: java xml spring aop


    【解决方案1】:

    添加这个:

    <aop:config>
        <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Fizz.foo(..))"/>
        <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Buzz.wapap(..))"/>
    </aop:config>
    

    您还需要在适合您框架的版本中添加 AOP 命名空间声明:

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

    还可以考虑使用@AspectJ切面,看看这个问题:Spring: Standard Logging aspect (interceptor)

    【讨论】:

    • 感谢 Tomasz,但看起来那些会为任何 Fizz 或 Buzz 方法调用日志拦截器建议。我需要它来指定 foo() 和 wapap()。我还需要添加 xmlns 的东西来处理新的 aop 标签吗?
    • 所有这些记录在哪里?我一直在寻找一些关于 Spring AOP 框架的 XML 模式指南,但没有找到!!!另外,如果我有一个 ExceptionInterceptor(实现 ThrowsAdvice)来处理抛出异常的情况。如何修改这些切入点字符串以指定任何异常?
    【解决方案2】:

    如果您使用的是 Spring 2.5+,您可以使用注释来创建您的建议和切入点。

    使用@Aspect 注释创建类。

    为特定类和特定方法创建@PointCut,然后创建@Around 建议。

    您可以在此处阅读如何操作的简短教程:

    http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/

    这很容易实现。

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 2012-11-05
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多