我在尝试在Spring配置中创建地图时遇到了麻烦,因为我定义的键会在地图自动装配时被替换。
我在spring-config.xml中定义了地图
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="basePackageWhereMyBeansAre"/>
<util:map id="beanMapper" map-class="java.util.HashMap">
<entry key="QueryType1" value-ref="bean1"/>
<entry key="QueryType2" value-ref="bean2"/>
</util:map>
</beans>
我尝试在我的Java代码中自动装配地图:
@Resource
Map<String, BeanSuperClass> beanMapper;
@Autowired
DefaultBeanClass defaultBean;
public String callMethod(Query query) {
BeanSuperClass bean = beanMapper.getOrDefault(query.getTypeName(), defaultBean);
...
}
问题在于,当我调试Java代码并检查beanMapper对象时,我可以看到条目的键被bean名称替换:
beanMapper {
entry: key="bean1" (the bean name), value=bean1 (the actual bean)
entry: key="bean2" (the bean name), value=bean2 (the actual bean)
}
所以beanMapper.getOrDefault()总是返回defaultBean。
有谁知道为什么更换钥匙?我做错了什么?
提前致谢