Is there a mechanism in Spring which provides a way for automation of generic beans construction?
For, example if I have a class definition like:
class Foo<T> {
private final T type;
...
}
and dependency like:
@Autowired
private Foo<String> foo;
I'd like to use some mechanism in Spring which provides, in some form, T from dependency definition (in above example, String) and provides a way for automatic instance creation?
The question is a little old, but doesn't contain an answer with example, so...
Using ResolvableType:
public <E> Foo<E> produceFoo(final InjectionPoint ip) {
ResolvableType resolved = ResolvableType.forField(ip.getField());
Foo<E> fooInstance = new FooImpl<>();
Class<E> parameterClass = (Class<E>) resolved.getGeneric(0).resolve();
fooInstance.doSomethingWithParametrized(parameterClass);
return fooInstance;
}
InjectionPoint cames from: import org.springframework.beans.factory.InjectionPoint;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With