[英]Spring - Classcast exception as CGLIB proxy cannot be forced
這是使我發瘋的情況。
<aop:config proxy-target-class="true">
-但我是新手,使用它似乎無濟於事。 問題:如何告訴Spring我需要一個針對Other類的CGLib代理?
以下代碼因classcastexception失敗。
Exception in thread "main" java.lang.ClassCastException: $Proxy4 cannot be cast to scratch.Other
at scratch.App$$EnhancerByCGLIB$$82d16307.createOther(<generated>)
at scratch.App.main(App.java:19)
App.java:
public class App {
public Other createOther() {
throw new UnsupportedOperationException();
}
public static void main(final String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
App app = (App) context.getBean("app");
Other oth = app.createOther();
oth.doSomething();
System.out.println("Other created");
}
}
** Other.java **
public interface OtherInterface {
}
class Other implements OtherInterface {
@Async
public void doSomething() {
System.out.println("did something");
}
}
** appcontext.xml **
<?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:task="http://www.springframework.org/schema/task"
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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:config proxy-target-class="true"></aop:config>
<bean name="app" class="scratch.App">
<lookup-method bean="otherBean" name="createOther" />
</bean>
<bean name="otherBean" class="scratch.Other" scope="prototype">
</bean>
<task:executor id="workflowExecutorSvcPool" pool-size="5-50"
queue-capacity="1000" keep-alive="60" />
<task:annotation-driven executor="workflowExecutorSvcPool" />
</beans>
一切似乎都很好-這是告訴spring使用cglib代理的正確方法。 實際上, 文檔指出默認情況下它將成為cglib代理。 唯一的要求是在類路徑上具有cglib。 確保您有cglib jar。
task:annotation-driven
元素應支持自己的proxy-target-class
屬性,例如,對於cglib代理,需要將其設置為true
Other oth = app.createOther();
這是問題所在。 由於返回的對象實際上是代理,因此createOther()
方法應返回該代理將實現的OtherInterface
。
它試圖將OtherInterface
的代理版本OtherInterface
為Other
類,但失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.