簡體   English   中英

春季-無法強制使用CGLIB代理作為Classcast異常

[英]Spring - Classcast exception as CGLIB proxy cannot be forced

這是使我發瘋的情況。

  1. 我有一個具有查找方法的類-createOther()
  2. createOther應該創建其他類型的對象。 其他工具OtherInterface,另外還有一個方法doSomething,標記為@Async
  3. 由於Other實現了OtherInterface,因此Spring給了我一個我不能轉換為Other的JDK代理。
  4. 春季文檔建議使用<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的代理版本OtherInterfaceOther類,但失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM