4

这是让我发疯的场景。

  1. 我有一个具有查找方法的类 - createOther()
  2. createOther 应该创建一个其他类型的对象。其他实现 OtherInterface 并且还有一个方法 doSomething 被标记为@Async
  3. 由于 Other 实现了 OtherInterface,因此 Spring 为我提供了一个无法转换为 Other 的 JDK 代理。
  4. Spring 文档建议使用<aop:config proxy-target-class="true">- 但我是新手,使用它似乎没有帮助。

问题:如何告诉 Spring 我需要一个针对 Other 类的 CGLib 代理?

下面的代码因类转换异常而失败。

    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)

应用程序.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

一切似乎都很好——这是告诉 spring 使用 cglib 代理的正确方法。事实上,文档声明它默认会生成 cglib 代理。唯一的要求是在你的类路径中有 cglib。确保你有 cglib jar。

于 2011-04-10T08:49:37.357 回答
1

task:annotation-driven元素应该支持proxy-target-class它自己的属性,对于 cglib 代理,该属性需要设置为 true,例如

于 2011-04-11T10:39:18.177 回答
0
Other oth = app.createOther();

这条线是问题所在。由于返回的对象实际上是一个代理,该方法createOther()应该返回OtherInterface代理将实现的一个。

它试图将代理版本OtherInterface转换为Other类并失败。

于 2014-09-10T11:20:42.420 回答