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层接口

 1 package com.pro.service;
 2 
 3 /**
 4  * 用户操作接口
 5  */
 6 public interface IUserService {
 7     public void add();//添加方法
 8     public void update();//修改方法
 9     public void delete();//删除方法
10     public void query();//查询方法
11 }

 定义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("查询方法");
    }

}
View Code

配置文件代码

<?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>

 测试代码

 1 package com.pro.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.pro.service.IUserService;
 7 import com.pro.service.impl.UserServiceImpl;
 8 
 9 public class TestSpring {
10     public static void main(String[] args) {
11         ApplicationContext ac=new ClassPathXmlApplicationContext("config.xml");
12         UserServiceImpl u=(UserServiceImpl)ac.getBean("userService");
13         u.add();
14     }
15 }

二、原因分析

   Spring AOP实现方式有两种,一种使用JDK动态代理,另一种通过CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理,所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理,创建的代理类是目标类的子类。

   显然,本工程中实现了一个接口,所以该是通过JDK动态代理来实现AOP的。

三、解决方案

1.在配置文件中配置proxy-target-class="true"

<aop:aspectj-autoproxy proxy-target-class="true"/>
2.将目标类型改为接口类型

原文地址:https://www.cnblogs.com/UnwillingToMediocrity/p/7994222.html