4

これが私を夢中にさせているシナリオです。

  1. 私はルックアップメソッドを持つクラスを持っています - createOther()
  2. createOther は、タイプ Other のオブジェクトを作成する必要があります。Other は OtherInterface を実装し、さらに @Async とマークされたメソッド doSomething を持っています
  3. Other は OtherInterface を実装しているため、Spring は、Other としてキャストできない JDK プロキシを提供します。
  4. Spring のドキュメントでは使用<aop:config proxy-target-class="true">が推奨されていますが、私はその初心者であり、それを使用しても役に立たないようです。

質問: Other クラスをターゲットとする CGLib プロキシが必要であることを Spring に伝えるにはどうすればよいですか?

以下のコードは、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");
}

}

** その他.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>
4

3 に答える 3

1

このtask:annotation-driven要素はproxy-target-class、cglib プロキシに対して true に設定する必要がある独自の属性をサポートする必要があります。たとえば、

于 2011-04-11T10:39:18.177 に答える
1

すべて問題ないようです。これは、Spring に cglib プロキシを使用するように指示する適切な方法です。実際、ドキュメントには、デフォルトで cglib プロキシを作成すると記載されています。唯一の要件は、クラスパスに cglib があることです。cglib jar があることを確認します。

于 2011-04-10T08:49:37.357 に答える
0
Other oth = app.createOther();

この行が問題です。返されるオブジェクトは実際にはプロキシであるため、メソッドはプロキシが実装する をcreateOther()返す必要があります。OtherInterface

OtherInterfaceのプロキシ バージョンをOtherクラスにキャストしようとして失敗しました。

于 2014-09-10T11:20:42.420 に答える