我有一个由 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/