java—在运行时自动连接带有泛型类型参数的bean

n1bvdmb6  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(346)

是的,所以我已经在这方面做了一段时间了,希望得到一些建议。
我有一个带类型化参数的类栏,我需要连接它。

@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>.

现在我明白了这个问题是因为我在初始化的bean时没有提到类型化参数 Bar 类使用 ApplicationContext . Question is, what might be the right syntax to mention the typed parameter <Detail> in the above statement?

hiz5n14c

hiz5n14c1#

我猜是这样的:

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

相关问题