Search code examples
javaspring-bootgenericstype-safety

Autowiring Beans with Generic typed parameters at runtime


Right, so I've been pulling my hairs on this for a while now and would love some suggestions.

I've got a class Bar with a typed argument that I need to wire.

@Component
@RequiredArgsConstructor
@Scope(value = "prototype")
public class Bar<T> extends Foo<T> {

private final Utility utility;

public Bar<T> init(String a, int b) {
    //initializations
}

//some more methods

}

The way I see it, I can wire the class using ApplicationContext like so,

Foo<Detail> foo = applicationContext.getBean(Bar.class).init(a,b);

But this throws in a warning,

Type safety: The expression of type Bar needs unchecked conversion to conform to Foo<Detail>.

Now I understand this issue is because I've failed to mention the typed parameter while initializing the bean of Bar class using ApplicationContext.

Question is, what might be the right syntax to mention the typed parameter <Detail> in the above statement?


Solution

  • Something like this, I guess:

    String [] names = context.getBeanNamesForType(ResolvableType.forClassWithGenerics(Bar.class, Detail.class));
    Foo<Detail> bar = context.getBean(names[0]);