java - 如何拥有一个带有2个接口(interface)的Spring动态代理?

标签 java spring proxy dynamic-proxy

我有一个由 Spring 注入(inject)到我的类中的对象(JdbcCursorItemReader 如果你关心的话)。

它实现了 5 个接口(interface),其中两个是我关心的(ItemReader、ItemStream)。如果我将我的类编码为其中之一,Spring 动态代理就会被正确注入(inject),我可以调用它的方法

private ItemReader blah;
public void setItemReader( blah ) { this.blah = blah };

酷,这按预期工作。如果我想基于 ItemStream 接口(interface)执行某些操作,我也可以将其转换为 ItemStream:

((ItemStream))blah.close();

酷,这让我可以访问这两个类的方法。然而,我不喜欢选角,并且知道哪里有更好的 Spring Magic 方法来做到这一点。我想到的方法是制作一个结合两者的界面:

public interface IStreamingItemReader<T> extends ItemReader<T>, ItemStream {
}

这让我的代码可以同时使用这两种...但代理注入(inject)可以预见地会失败。

Failed to convert property value of type [$Proxy0 implementing org.springframework.beans.factory.InitializingBean,org.springframework.batch.item.ItemReader,org.springframework.batch.item.ItemStream,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [blah.IStreamingItemReader] for property 'itemReader'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [$Proxy0 implementing org.springframework.beans.factory.InitializingBean,org.springframework.batch.item.ItemReader,org.springframework.batch.item.ItemStream,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [blah.IStreamingItemReader] for property 'itemReader': no matching editors or conversion strategy found

引起我注意的部分是 未找到匹配的编辑器或转化策略

有没有办法教 Spring 当它看到 JdbcCursorItemReader 时,创建 IStreamingItemReader 的代理?

我意识到我可以使用 CGLib 和基于类的代理来解决这个问题...但如果我可以将其保留为动态接口(interface)代理,我会更高兴...

最佳答案

简单的方法:如果可能的话,让你的实现类实现你的联合接口(interface)而不是两个单独的接口(interface)。

不太清晰的方法,但不引入额外的类(需要泛型):

public interface A { }

public interface B { }

public class C implements A, B { }

public class D {
    private A a;
    private B b;

    public <T extends A & B> void setObject(T o) {
        this.a = o;
        this.b = o;
    }

    public static void main(String[] args) {
        D d = new D();
        d.setObject(new C());
    }
}

关于java - 如何拥有一个带有2个接口(interface)的Spring动态代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4219143/

相关文章:

java - XmlWebApplicationContext、AnnotationConfigWebApplicationContext 和 GenericWebApplicationContext 之间有什么区别

java - Tapestry5编译错误在服务定位器方法中返回服务接口(interface)

apache 2.4.6 代理 https 到 http Tomcat 7.0.68

java - 使用java将音频文件与文本匹配

java - 如何制作 BufferedReader 的副本?

java - 通过将源代码复制到我的项目来调试 rt.jar 中的类

node.js - 如何充当代理服务器并修改传入的请求,然后在 NodeJS 中转发它们?

java - 在创建 bean 时订购第 3 方 Spring 过滤器

java - 为什么 JAR 文件不包含文档?

http - 读取缓冲区并将其重写为 Go 中的 http.Response