【问题标题】:Autowiring Beans with Generic typed parameters at runtime在运行时使用通用类型参数自动装配 Bean
【发布时间】:2020-12-31 15:17:30
【问题描述】:

好的,所以我一直在努力解决这个问题,希望得到一些建议。

我有一个类 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>.

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

Question is, what might be the right syntax to mention the typed parameter &lt;Detail&gt; in the above statement?

【问题讨论】:

    标签: java spring-boot generics type-safety


    【解决方案1】:

    我猜是这样的:

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

    【讨论】:

    • 这也行不通,伙计。似乎我忘了提到Detail 不是一个弹簧管理的bean,而是一个普通的旧java bean 类。在这种情况下,您有其他解决方法吗?
    • @AJC 我明白了。问题是你(通过@Component)将一个通用的bean Bar&lt;T&gt; 放入spring 上下文中。检索它的唯一方法是通过context.getBeanNamesForType(ResolvableType.forClass(TestConfig.Bar.class))context.getBeanNamesForType(ResolvableType.forClassWithGenerics(TestConfig.Bar.class, Object.class));。通常反过来,你定义一个通用接口并添加 2 个或更多实现该接口的通用 Spring bean。
    • 我听到了。我想我需要重新设计一下。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多