我再学习spring aop遇到的问题和解决方案

来源:互联网 发布:什么是计算机编程 编辑:程序博客网 时间:2024/06/05 17:58

今天我在学习spring的切面,我傻傻的以为使用了spring的原包就好了其实不是这样的。我都要哭了可怜可怜

首先在遇到的情况是

org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [resource/applicationContext.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

经过查找 是缺失 aopalliance-1.0.jar包 这个包还有另外的名字com.springsource.org.aopalliance-1.0.0.jar


之后还是错大哭大哭大哭 

好像是没找到org.aspectj.lang.JointPoint之类的巴拉巴拉.....

问谷歌是没有aspectjweaver.jar包

将这个包加入到类库中

之后好了吧,错啊

我是这么配置我的applicationContext的

<context:component-scan base-package="com.springidol"/><aop:config>        <aop:aspect ref="audience">            <aop:before pointcut="execution(* com.springidol.Performer.perform (..))" method="takeSeats" />              <aop:before pointcut="execution(* com.springidol.Performer.perform(..))" method="turnOffCellPhones" />              <aop:after-returning pointcut="execution(* com.springidol.Performer.perform(..))"  method="applaud" />             <aop:after-throwing pointcut="execution(* com.springidol.Performer.perform(..))" method="demandRefund" />        </aop:aspect>    </aop:config>

这是我的Performer的代码


public interface  Performer {    void perform();}
这是我的Instrumentalist类的代码

@Componentpublic class Instrumentalist implements Performer { private String song; @Autowired private Instrument instrument; public Instrumentalist(){ } public void perform(){ System.out.print("Playing "+song+" :"); instrument.play(); } public void setSong(String song){ this.song=song; } public String getSong(){ return song; } public String streamSong(){ return song; } public void setInstrument(Instrument instrument){ this.instrument=instrument; }}


在测试文件中我是这样写的

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");//放在默认的类文件夹下Instrumentalist instrumentalist=(Instrumentalist)ctx.getBean("instrumentalist");instrumentalist.perform();

还是错  ClassCastException: $Proxy0 cannot be cast to Instrumentalist.class


必须将 Instrumentalist转换成接口类型,否则会包ClassCastException 的错误 

就像这样子

Performer instrumentalist=(Performer)ctx.getBean("instrumentalist");

学院派的解释

spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理,如果被代理的目标对象实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。使用beanNameAutoProxyCreator来进行事务代理的话,他的proxyTargetClass这个属性设置为false(默认是false),即使用JDK动态代理,如果你的service类没有实现接口的话,就会报类型转换错误。

看不懂


终于能运行出来了 

the audience is taking their seats
the audience is turning off their cellphone
Playing null :TOOT TOOT TOOT
CLAP CLAP CLAP

-----------------------------------------------------------------------------------

summary:

如果你使用原始的netbeans给你添加的类库开始学习spring aop 你需要

1. 放置com.springsource.org.aopalliance-1.0.0.jar到你的库中

2.放置aspectjweaver.jar到你的库中

3.当你用getBean的方式的到配置文件中的使用接口类的时候,必须强制转换为接口类型

详细的spring的使用推荐阅读

http://blog.csdn.net/eric_sunah/article/details/17385801


0 0
原创粉丝点击