[英]Not able to inject Bean
我试图使用java bean注入。 它是一个非常基本的实现,但注入不起作用。 你能指导我吗?
test.java
public class TempClass{
@Autowired
HashMap<String,HashMap<String,String>> newMap = new HashMap<String,HashMap<String,String>>();
public void setNewMap(HashMap<String, HashMap<String,String>> newMap)
{
newMap= newMap;
}
public HashMap<String, HashMap<String,String>> getNewMap()
{
return newMap;
}
}
另外:对于我的bean配置conn.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<util:map id="xyz" map-class="java.util.HashMap">
<entry key="x" value-ref="x" />
<entry key="y" value-ref="y" />
<entry key="z" value-ref="z" />
</util:map>
<util:map id="x" map-class="java.util.HashMap">
<entry key="xx" value="xx" />
<entry key="xy" value="xy" />
<entry key="xz" value="xz" />
</util:map>
<util:map id="y" map-class="java.util.HashMap">
<entry key="yx" value="yx" />
<entry key="yy" value="yy" />
<entry key="yz" value="yz" />
</util:map>
<util:map id="z" map-class="java.util.HashMap">
<entry key="zx" value="zx" />
<entry key="zy" value="zy" />
<entry key="zz" value="zz" />
</util:map>
<bean id="bean123" class="reference.to.class" autowire="byName">
<property name="newMap" ref="xyz" />
</bean>
</beans>
有人可以指导我什么是错的吗?
@Autowired注释应该在您要注入的字段上方 。 并且不应仅声明该字段。
此外,注入地图并不是最简单的示例。 你应该编写一个更简单的测试用例来获取它。 例如,
package test;
public class SpringInjectionTest {
@Autowired
private String injectThis;
public void setInjectThis(String s) {
injectThis = s;
}
public String getInjectThis() {
return injectThis;
}
}
这是applicationContext:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<bean id="testBean" class="test.SpringInjectionTest" autowire="byName"/>
</beans>
您有两种可能的修复方法:
一种。 将newMap
声明为Map<String, Map<String, String>>
而不是具体的Hashmap,这是因为internal util:map
返回Map
的对象类型,autowiring将无法找到合适的候选者。
湾 从newMap
删除@Autowired
, newMap
通过xml直接注入依赖项,就像你做的那样:
<bean id="bean123" class="...">
<property name="newMap" ref="xyz" />
</bean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.