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.