gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:36:52 25 4
gpt4 key购买 nike

我有一个对象被 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();

太棒了,这让我可以访问这两个类的方法。但是,我不是 Actor 的粉丝,并且知道在哪里必须有更好的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com