如何在Spring语境中纠正bean的注入映射

时间:2014-05-13 11:39:32

标签: java spring

我在spring应用程序中使用组件扫描。所以在spring上下文中我创建了map:

<util:map id="mapByName" map-class="java.util.concurrent.ConcurrentHashMap">
    <entry key="Name1" value-ref="MyCustomClassName1" />
</util:map>

在我的类中注释@Service我想注入这个属性:

@Inject
private Map<String, MyCustomClassName1> mapByName;

这仍然有效。只是以钥匙的名义出现的问题。当我打印这个属性时,我得到了[MyCustomClassName1=org.my.package.service.MyCustomClassName1@cb52f2]

因此您可以看到密钥的名称已从Name1-&gt; MyCustomClassName1(此类的名称)更改。所以我的问题是如何在map属性中定义自定义键名?

2 个答案:

答案 0 :(得分:11)

如果我是你,我会使用Java Config创建Map,因为Java是创建Java对象的最佳方式:) :)。 您的配置代码如下所示:

@Bean(name = "mapBean")
public Map<String, MyCustomClassName1> mapBean() {
    Map<String, MyCustomClassName1> map = new HashMap<>();
    //populate the map here - you will need to @Autowire the references if they are not defined in this configuration
    return map;
}

然后我会将它注入所需的任何地方:

@Resource(name="mapBean")
private Map<String, MyCustomClassName1> map;

请注意使用@Resource代替@Autowired@Inject

答案 1 :(得分:6)

引自the documentation

  

自动装配的Maps值将包含与预期类型匹配的所有bean实例,而Maps键将包含相应的bean名称。

我认为仅使用@Inject更改@Resource即可。