Description
Oliver Drotbohm opened SPR-9965 and commented
Currently the container considers List
and Map
types being injected as special injection points and uses generics inspection to inject the appropriate Spring beans. However, there's no general support for injecting generic types in a type safe way.
Assuming we have a generic interface:
interface MyGenericType<T> { ... }
and two Spring beans:
class IntegerType extends MyGenericType<Integer> { ... }
class StringType extends MyGenericType<String> { ... }
A client trying to get a special instance of the generic type looking like this:
class MyClient {
@Autowired
private List<MyGenericType<Integer>> dependencies;
}
currently not only gets injected the IntegerType
bean but the StringType
as well which will cause exceptions at runtime. The core reason this is the case is that the BeanFactory
currently uses Class<?>
based type information that does not carry the generics information on injection time and selectvely inspects the generics for injection of special types like List
and Map
.
The Spring Data Commons project has a TypeInformation
abstraction that allows to lazily resolve generics information as it keeps the generics information around when traversing types, property, method parameter and method return types. It could serve as foundation for an improvement of the BeanFactory
.
Issue Links:
- Introduce ResolvableType Class [SPR-10973] #15601 Introduce ResolvableType Class ("depends on")
- Generic autowiring should support wiring of components with unresolved type variables [SPR-10993] #15621 Generic autowiring should support wiring of components with unresolved type variables
- autowiring doesn't match generics [SPR-5546] #10217 autowiring doesn't match generics
- Add generics / parameterized type support to ListableBeanFactory getBeanNamesForType/getBeansOfType methods [SPR-12147] #16761 Add generics / parameterized type support to ListableBeanFactory getBeanNamesForType/getBeansOfType methods
5 votes, 13 watchers