spring aop学习中遇到的问题——error at ::0 formal unbound in pointcut

来源:互联网 发布:java 局域网聊天室 编辑:程序博客网 时间:2024/06/05 08:32

本来想写一个简单的aop例子跟踪一下源码,但是写好了之后发现出现了error at ::0 formal unbound in pointcut错误,发现是因为在配置文件中对进行要拦截的方法没有注意的参数的注入,就是说,你要拦截的方法中有参数,那么在配置文件的aspect的expression中也需要有 and args(methodName)。但是在配置的时候一定要注意想要拦截的方法里面有参数,需要对方法里面的参数进行处理,但是在配置aop的时候,写成了切面aspect中方法的参数,导致aspect中配置的方法在要拦截的类中找不到相匹配的方法,所以没有拦截到任何方法,下面附上代码:
要拦截的类的方法,注意参数:

public class HelloWorld {    public void saySome(String methodName){        for (int i = 0; i < 10; i++) {            System.out.println("hello world methodName");        }    }}

截面:

public class CountingBeforeAdvice extends MethodCounter{    public void before(String methodName)            throws Throwable {        System.out.println(methodName);    }}

测试:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class CountingBeforeAdviceTest {    @Autowired    private ApplicationContext applicationContext;    @Test    public void testCountering() {        HelloWorld world = (HelloWorld) applicationContext.getBean("helloWorld");        for(int i = 0; i < 10; i++){            world.saySome("methodName________" + i);        }    }}

配置文件

    <bean id="countingBeforeAdvice"        class="com.youxigu.spring.aop.aspect.example.methodcounter.CountingBeforeAdvice"/>    <bean id="helloWorld"        class="com.youxigu.spring.aop.aspect.example.methodcounter.HelloWorld" />    <aop:config proxy-target-class="true">        <aop:aspect ref="countingBeforeAdvice">            <aop:pointcut id="target"                expression="execution(* spon.spring.aop.aspect.example.methodcounter.HelloWorld.saySome(..)) and args(methodName)"/>            <aop:before method="before" pointcut-ref="target"/>        </aop:aspect>    </aop:config>

需要注意的是:expression=”execution(* spon.spring.aop.aspect.example.methodcounter.HelloWorld.saySome(..)) and args(methodName)”中最后的and args(methodName),这其中写的是要拦截的方法中的参数,也就是上面helloworld中的方法的参数,不是countingBeforeAdvice中的方法。还有就是这两个方法中的参数个数和顺序一定要一样,不然也会报错。

0 0