如何自动装配泛型类型 <T>在春天? [英] How to Autowire Bean of generic type <T> in Spring?

查看:30
本文介绍了如何自动装配泛型类型 <T>在春天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 bean Item,它需要在 @Configuration 类中自动装配.

I have a bean Item<T> which is required to be autowired in a @Configuration class.

@Configuration
public class AppConfig {

    @Bean
    public Item<String> stringItem() {
        return new StringItem();
    }

    @Bean
    public Item<Integer> integerItem() {
        return new IntegerItem();
    }

}

但是当我尝试 @Autowire Item 时,出现以下异常.

But when I try to @Autowire Item<String>, I get following exception.

"No qualifying bean of type [Item] is defined: expected single matching bean but found 2: stringItem, integerItem"

我应该如何在 Spring 中自动装配泛型类型 Item?

How should I Autowire generic type Item<T> in Spring?

推荐答案

简单的解决方案是升级到Spring 4.0 因为它会自动将泛型视为 @Qualifier 的一种形式,如下所示:

Simple solution is to upgrade to Spring 4.0 as it will automatically consider generics as a form of @Qualifier, as below:

@Autowired
private Item<String> strItem; // Injects the stringItem bean

@Autowired
private Item<Integer> intItem; // Injects the integerItem bean

事实上,您甚至可以在注入列表时自动装配嵌套泛型,如下所示:

Infact, you can even autowire nested generics when injecting into a list, as below:

// Inject all Item beans as long as they have an <Integer> generic
// Item<String> beans will not appear in this list
@Autowired
private List<Item<Integer>> intItems;

这是如何工作的?

新的ResolvableType 类提供了实际使用泛型类型的逻辑.您可以自己使用它来轻松导航和解析类型信息.ResolvableType 上的大多数方法本身都会返回一个 ResolvableType,例如:

The new ResolvableType class provides the logic of actually working with generic types. You can use it yourself to easily navigate and resolve type information. Most methods on ResolvableType will themselves return a ResolvableType, for example:

// Assuming 'field' refers to 'intItems' above
ResolvableType t1 = ResolvableType.forField(field); // List<Item<Integer>> 
ResolvableType t2 = t1.getGeneric(); // Item<Integer>
ResolvableType t3 = t2.getGeneric(); // Integer
Class<?> c = t3.resolve(); // Integer.class

// or more succinctly
Class<?> c = ResolvableType.forField(field).resolveGeneric(0, 0);

查看示例以下链接中的教程.

Check out the Examples & Tutorials at below links.

希望对你有帮助.

这篇关于如何自动装配泛型类型 &lt;T&gt;在春天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆