日期:2014-05-18  浏览次数:20672 次

Spring AOP的自动代理的一个小Demo无法找到错误所在: BeanNameAutoProxyCreator
我做的小Demo,是关于Spring AOP自动代理的BeanNameAutoProxyCreator这个类,即根据名称来自动代理.我把代码贴出来,还有运行结果,大家帮我看看吧.(我用另一个代理方法,DefaultAdvisorAutoProxyCreator,是没有问题的)

两个被代理的Bean

public class TestBeanA {
public void sayHello() {
System.out.println("Hello, Autoproxy");
}
}

public class BeanB {
public void sing() {
System.out.println("有个大中国啊,我们是一家!");
}
}


我写的前置通知:

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println(method.getName() + "(),方法即将运行...");
}
}


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" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanA" class="com.chenjb.aop.autoproxy.TestBeanA"/>
<bean id="beanB" class="com.chenjb.aop.autoproxy.BeanB"/>
<bean id="beforeAdvice" class="com.chenjb.aop.autoproxy.BeforeAdvice"/>

<bean 
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>Bean*</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>beforeAdvice</value>
</list>
</property>
</bean>
</beans>


测试类:

@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"autoproxyname.xml", TestBeforeAdvice.class);
TestBeanA beanA = ctx.getBean("beanA", TestBeanA.class);
beanA.sayHello();
BeanB beanB = ctx.getBean("beanB", BeanB.class);
beanB.sing();
}


运行结果:
Hello, Autoproxy
有个大中国啊,我们是一家!

运行结果中并没有打印出前置通知里面的那个方法,所以根本就没有执行前置通知,大家帮我看下是哪里出错啦!

------解决方案--------------------
<value>Bean*</value> B要小写啊