可以春天@Autowired地图? [英] Can spring @Autowired Map?

查看:216
本文介绍了可以春天@Autowired地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是地图

@Autowired
private Map<String, ISendableConverter> converters;

ISendableConverter

public interface ISendableConverter {

    ISendableMsg convert(BaseMessage baseMessage);

    String getType();
}

有几个类实现 ISendableConverter

我想使用spring Autowried将它们注入变量 converter

i want to inject them into the variable converters by using spring Autowried.

类的实例为值,方法 getType()的结果为键。

the instance of class as value, and the result of method getType() as key.

喜欢这个

@Component
public class SendableVoiceMsgConverter implements ISendableConverter {

    @Override
    public ISendableMsg convert(BaseMessage baseMessage) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getType() {
        return "VOICE";
    }
}

这可能吗?以及如何?

推荐答案

尝试使用 @资源 - 我还没有测试过这段代码。

Try with something like @Resource - I have not tested this code.

@Resource(name="converters")
private Map<String, ISendableConverter> converters;

@Value("#{converters}")
private Map<String, ISendableConverter> converters;

来自 Spring Docs



(..)无法通过@Autowired注入自身定义为集合或地图类型的bean,因为类型匹配不适用于它们。对于此类bean,请使用 @Resource ,并参考具体内容按唯一名称收集或映射bean。

(..) beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.


只有在准备<$ c时这才有效$ c>转换器像这样的bean:

This should work, only if you prepare converters bean like this:

<util:map id="converters" scope="prototype" map-class="java.util.HashMap" 
          key-type="java.lang.String" value-type="...ISendableConverter">
    <entry key="VOICE" value="sendableVoiceMsgConverter" />
</util:map>

这也是类似的问题:

  • Auto-wiring a List using util schema gives NoSuchBeanDefinitionException
  • Spring can't autowire Map bean

这篇关于可以春天@Autowired地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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