代码之家  ›  专栏  ›  技术社区  ›  Radek Anuszewski

Spring AOP前后方法不适用于XML配置

  •  0
  • Radek Anuszewski  · 技术社区  · 9 年前

    我有一个方面,目前没有什么特别之处:

    @Named
    public final class PreventNullReturn {
        public void replaceNullWithSpecialCase() {
            System.out.print("ASPECT CALLED!");
            throw new AssertionError();
        }
    }
    

    它应该抛出一个错误来证明它被调用了。我有 spring-aspects.xml 声明方面的文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <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"
    >
        <aop:aspectj-autoproxy/>
    
        <bean class="aspects.PreventNullReturn"
              id="preventNullReturn"
        ></bean>
    
        <aop:config>
            <aop:aspect
                    ref="preventNullReturn"
            >
                <aop:pointcut
                        id="preventNull"
                        expression="execution(* *.getById(..))"
                ></aop:pointcut>
                <aop:before
                        pointcut-ref="preventNull"
                        method="replaceNullWithSpecialCase"
                ></aop:before>
                <aop:after
                        pointcut-ref="preventNull"
                        method="replaceNullWithSpecialCase"
                ></aop:after>
            </aop:aspect>
        </aop:config>
    </beans>
    

    在Spring单元测试的配置文件中,我这样使用它:

    <import resource="classpath*:spring-aspects.xml" />
    

    但方面并没有被调用。 有趣的是,甚至IDE显示 Navigate to advised methods 工具提示,它可以正确导航。我试着跟随 "Spring in Action, Fourth Edition book 在第章中 1.1.3. Applying aspects (这就是我使用XML而不是类的原因),但我做错了什么,我想不出来。如果我能提供更多有用的细节,请来信。如果你决定帮助我,我会很感激的,提前谢谢你。

    1 回复  |  直到 9 年前
        1
  •  0
  •   Radek Anuszewski    9 年前

    我自己找到了一个答案,而不是将其作为配置文件中的资源导入Spring单元测试:

    <import resource="classpath*:spring-aspects.xml" />
    

    我必须将其内容直接放在Spring单元测试的配置文件中:

     <!--TODO: Move it to separated file-->
    <aop:aspectj-autoproxy/>
    
    <bean class="aspects.PreventNullReturn"
          id="preventNullReturn"
    ></bean>
    
    <aop:config>
        <aop:aspect
                ref="preventNullReturn"
        >
            <aop:pointcut
                    id="preventNull"
                    expression="execution(* *.getById(..))"
            ></aop:pointcut>
            <aop:before
                    pointcut-ref="preventNull"
                    method="replaceNullWithSpecialCase"
            ></aop:before>
            <aop:after
                    pointcut-ref="preventNull"
                    method="replaceNullWithSpecialCase"
            ></aop:after>
        </aop:aspect>
    </aop:config>
    

    当然,哪一种解决方案比将其放在单独的文件中更糟糕,但这是我使其工作的唯一方法。