Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring generic bean factory

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?

like image 976
Lovro Pandžić Avatar asked Mar 09 '23 07:03

Lovro Pandžić


1 Answers

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;

like image 106
RicardoS Avatar answered Mar 20 '23 21:03

RicardoS