spring aop开发常见错误
1.
1 Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [spring-aop.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice
解决方法:
下载引入 aopalliance-1.0.jar
使用spring aop 一般需要的依赖jar有: aopalliance-1.0.jar(AOP联盟的API包,里面包含了针对面向切面的接口。 通常Spring等其它具备动态织入功能的框架依赖此包。) 、aspectjweaver-1.5.3.jar、javassist-3.9.0.GA.jar(Javassist的(JAVA编程助手)使Java字节码操纵简单。这是一个编辑Java字节码的类库)。
2.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Instrumentalist' defined in class path resource [spring-aop.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.AspectJPointcutAdvisor]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Pointcut is not well-formed: expecting 'illegal identifier start (。)' at character position 52 execution(* com.luchao.springaop.Performer.perform(。。))
解决方法:在工具下。。显示特别小,所有拿出来发现原来是。。的问题,把。。换成..就OK了。
3.
1 Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to com.luchao.springaop.Instrumentalist 2 at com.luchao.springaop.AspectTest.audienceShouldApplaud(AspectTest.java:13) 3 at com.luchao.springaop.AspectTest.main(AspectTest.java:19)
Spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。
所以,解决办法是,如果用JDK动态代理,就必须为被代理的目标实现一个接口(要注意的地方是:需要将ctx.getBean()方法的返回值用接口类型接收);如果使用CGLIB强制代理,就必选事先将CGLIB包导入项目,设置beanNameAutoProxyCreator的proxyTargetClass属性为true。
例如:
1 <aop:aspectj-autoproxy proxy-target-class="true"/>
解决方案:
1 public void audienceShouldApplaud() throws PerformanceException{ 2 Performer performer = (Performer) applicationContext.getBean("Instrumentalist"); 3 performer.perform(); 4 }