简体   繁体   English

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

[英]How to correct inject map of bean in spring context

I am using component-scan in my spring application. 我在我的spring应用程序中使用组件扫描。 So in spring context I created map: 所以在spring上下文中我创建了map:

<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). 因此,您可以看到键的名称已从Name1-> MyCustomClassName1(此类的名称)更改。 So my question is how to define custom key name in map property ? 所以我的问题是如何在map属性中定义自定义键名?

If I were you, I would use Java Config to create a Map, since Java is the best way to create a Java object :) :). 如果我是你,我会使用Java Config创建Map,因为Java是创建Java对象的最佳方式:) :)。 Your configuration code would look like this: 您的配置代码如下所示:

@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 @Resource instead of @Autowired or @Inject 注意使用@Resource而不是@Autowired@Inject

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 @Inject with @Resource will do it. 我认为只需用@Resource更改@Inject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM