Spring AOP 增强方法不执行原因
今天学习Spring 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="target" class="im.hwp.TargetImpl"></bean>
<bean id="myAspect" class="im.hwp.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(public void im.hwp.TargetImpl.say())"> </aop:before>
<aop:after method="after" pointcut="execution(public void im.hwp.TargetImpl.say())"> </aop:after>
</aop:aspect>
</aop:config>
</beans>
我自己定义的待增强类如下:
public class TargetImpl implements Target {
public void say(String s) {
System.out.println("say:"+s);
}
}
当时在写xml中pointcut的时候眼疾手快用tab键自动填充,结果就写成了这样:
execution(public void im.hwp.TargetImpl.say())
因为我在定义方法的时候要求提供一个参数,而我在xml配置切入点的时候方法中没有参数,因此在运营过程中自然就找不到这个切入点,一失足一下午就没了,以后写代码还是要小心。
将方法中参数删掉以后,单元测试结果终于正常了!输出如下:
前置代码增强
say:
后置代码增强