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.將目標類型改為接口類型

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM