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

hud*_*udi 6 java spring

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

<util:map id="mapByName" map-class="java.util.concurrent.ConcurrentHashMap">
    <entry key="Name1" value-ref="MyCustomClassName1" />
</util:map>
Run Code Online (Sandbox Code Playgroud)

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

@Inject
private Map<String, MyCustomClassName1> mapByName;
Run Code Online (Sandbox Code Playgroud)

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

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

geo*_*and 12

如果我是你,我会使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

@Resource(name="mapBean")
private Map<String, MyCustomClassName1> map;
Run Code Online (Sandbox Code Playgroud)

注意使用@Resource而不是@Autowired@Inject


And*_*fan 6

文档中引用:

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

我认为这只是改变@Inject@Resource将做到这一点.