Spring IoC 和通用接口类型 [英] Spring IoC and Generic Interface Type

查看:25
本文介绍了Spring IoC 和通用接口类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Spring IoC 与这样的接口一起使用:

I'm trying to use Spring IoC with an interface like this:

public interface ISimpleService<T> {
    void someOp(T t);
    T otherOp();
}

Spring 能否提供基于泛型类型参数 T 的 IoC?我的意思是,像这样:

Can Spring provide IoC based on the generic type argument T? I mean, something like this:

public class SpringIocTest {
    @Autowired
    ISimpleService<Long> longSvc;

    @Autowired
    ISimpleService<String> strSvc;
    //...
}

当然,我上面的例子不起作用:

Of course, my example above does not work:

expected single matching bean but found 2: [serviceLong, serviceString]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:957)

我的问题:是否可以在对接口或实现类进行最少修改的情况下提供类似的功能?例如,我知道我可以使用 @Qualifiers,但我想让事情尽可能简单.

My Question: is it possible to provide a similar functionality with minimum modifications to either the Interface or the implementing classes? I know for instance I can use @Qualifiers, but I want to keep things as simple as possible.

推荐答案

由于擦除,我认为这是不可能的.在进行全自动装配时,我们通常会切换到强类型子接口:

I do not believe this is possible due to erasure. We generally switched to strongly typed sub-interfaces when going for full-autowiring:

public interface LongService extends ISimpleService<Long> {}
public interface StringService extends ISimpleService<String> {}

在进行此切换后,我们发现我们实际上非常喜欢它,因为它使我们能够更好地进行查找使用"跟踪,而您在泛型接口中会丢失一些东西.

Upon doing this switch we found we actually liked this pretty well, because it allows us to do "find usage" tracking much better, something you loose with the generics interfaces.

这篇关于Spring IoC 和通用接口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆