Java 如何在 spring 上下文中更正 bean 的注入映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23630255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:24:14  来源:igfitidea点击:

How to correct inject map of bean in spring context

javaspring

提问by hudi

I am using component-scan in my spring application. So in spring context I created map:

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

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

and in my class annotated by @Service I want to inject this property:

在我用 @Service 注释的班级中,我想注入这个属性:

@Inject
private Map<String, MyCustomClassName1> mapByName;

this is still working. Problem just in name of key. When I print this property I got [MyCustomClassName1=org.my.package.service.MyCustomClassName1@cb52f2]

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

so as you can see name of key is changed from Name1->MyCustomClassName1 (Name of this class). So my question is how to define custom key name in map property ?

如您所见,键的名称已从 Name1->MyCustomClassName1(此类的名称)更改。所以我的问题是如何在 map 属性中定义自定义键名?

采纳答案by Andrei Stefan

Quote from the documentation:

文档中引用:

An autowired Maps values will consist of all bean instances that match the expected type, and the Maps keys will contain the corresponding bean names.

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

I think that just changing @Injectwith @Resourcewill do it.

我认为只要改变@Injectwith@Resource就可以了。

回答by geoand

If I were you, I would use Java Config to create a Map, since Java is the best way to create a Java object :) :). Your configuration code would look like this:

如果我是你,我会使用 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;
}

And then I would inject it into wherever it's needed like so:

然后我会将它注入到任何需要的地方,如下所示:

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

Note the use of @Resourceinstead of @Autowiredor @Inject

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