
正文
java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to...异常
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
异常:
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to com.pro.service.impl.UserServiceImpl
at com.pro.test.TestSpring.main(TestSpring.java:12)
一、抛异常的工程
定义Service层接口
package com.pro.service; /**
* 用户操作接口
*/
public interface IUserService {
public void add();//添加方法
public void update();//修改方法
public void delete();//删除方法
public void query();//查询方法
}
定义Service层实现类
package com.pro.service.impl;
import com.pro.service.IUserService;
public class UserServiceImpl implements IUserService {
@Override
public void add() {
System.out.println("增加方法");
}
@Override
public void update() {
System.out.println("修改方法");
}
@Override
public void delete() {
System.out.println("删除方法");
}
@Override
public void query() {
System.out.println("查询方法");
}
}
配置文件代码
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<import resource="config/user.xml"/>
<bean id="userService" class="com.pro.service.impl.UserServiceImpl"></bean>
<bean id="log" class="com.pro.aop.Log"></bean>
<bean id="logTwo" class="com.pro.aop.LogTwo"></bean>
<bean id="logThree" class="com.pro.aop.LogThree"></bean> <!-- 1.api使用aop -->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.pro.service.impl.*.*(..))"/>
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
</aop:config> </beans>
测试代码
package com.pro.test; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.pro.service.IUserService;
import com.pro.service.impl.UserServiceImpl; public class TestSpring {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("config.xml");
UserServiceImpl u=(UserServiceImpl)ac.getBean("userService");
u.add();
}
}
二、原因分析
Spring AOP实现方式有两种,一种使用JDK动态代理,另一种通过CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理,所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理,创建的代理类是目标类的子类。
显然,本工程中实现了一个接口,所以该是通过JDK动态代理来实现AOP的。
三、解决方案
1.在配置文件中配置proxy-target-class="true"
<aop:aspectj-autoproxy proxy-target-class="true"/>
2.将目标类型改为接口类型






