IDEA报错: class com.sun.proxy.$Proxy11 cannot be cast to ’XXXXX‘
今天在学习Spring事务配置的过程中,发生了如上错误。原程序如下:
public void testFindById(){
//获取ApplicationConext对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取AccountServiceImpl对象
IAccountService as = (AccountServiceImpl) ac.getBean("accountService");
//执行方法
System.out.println(as.findById(2));
}
该测试类方法测试了根据id查找account对象的功能。在没有配置事务的时候,程序可以正常执行,但是在根据AOP配置了事务之后,出现了题示问题。
**问题分析:**由于Spring AOP的动态代理机制如下:对于没有实现任何接口的类,采用CGLIB方法;对于实现了接口的对象,默认使用JDK动态创建代理对象。而AccountServiceImpl实现了IAccountService接口,所以在获取bean对象并进行强制转换时,要转换成父类userDao。
解决方法:所以将上述代码中小括号中的AccountServiceImpl改成IAccountService即可.
public void testFindById(){
//获取ApplicationConext对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取AccountServiceImpl对象
IAccountService as = (IAccountService) ac.getBean("accountService");
//执行方法
System.out.println(as.findById(2));
}