IoC和通用接口类型

IoC和通用接口类型

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

问题描述

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

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

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

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

当然,不工作:

 期望单个匹配的bean,但找到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)

我的问题:是否可以通过对Interface或实现类的最小修改来提供类似的功能?我知道例如我可以使用@Qualifiers,但我希望尽可能简单。

解决方案

我不相信这是可能的,因为擦除。我们通常在进行完全自动装配时切换到强类型的子接口:

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

在做这个转换之后,我们发现我们确实很喜欢这个,因为它可以让我们做查找使用情况跟踪效果要好得多,你用泛型界面放松了一些。


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

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

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)

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和通用接口类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:46