標籤:ack jdk cglib 對象 方案 檔案中 none 3.0 read
異常:
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.將目標類型改為介面類型
java.lang.ClassCastException: com.sun.proxy.$Proxy2 cannot be cast to...異常