在运行时使用通用类型参数自动装配 Bean

问题描述

是的,所以我已经为此纠结了一段时间,希望得到一些建议。

我有一个 Bar 类,其中包含一个我需要连接的类型参数

@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

}

在我看来,我可以像这样使用 ApplicationContext 连接类,

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

但这会引发警告,

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

现在我明白这个问题是因为我在使用 Bar 初始化 ApplicationContext 类的 bean 时没有提到类型参数。

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

解决方法

我猜是这样的:

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