spring map使用annotation泛型注入问题分析 (二)

2014-11-24 11:39:10 · 作者: · 浏览: 21
g.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:547)

查看spring的代码

[java]
else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
Class keyType = descriptor.getMapKeyType();
if (keyType == null || !String.class.isAssignableFrom(keyType)) {
if (descriptor.isRequired()) {
throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
"] must be assignable to [java.lang.String]");
}
return null;
}

else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
Class keyType = descriptor.getMapKeyType();
if (keyType == null || !String.class.isAssignableFrom(keyType)) {
if (descriptor.isRequired()) {
throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
"] must be assignable to [java.lang.String]");
}
return null;
}

也就是spring使用Autowired进入注入时,map的key类型只能为string,但是

如果我使用set方法注入后者构造方法注入,map的可以是可以自动转为integer的。


set方法注入,不要在set方法上使用antowired


[java]

public void setTypeMap(Map typeMap) {
this.typeMap = typeMap;
}

public void setTypeMap(Map typeMap) {
this.typeMap = typeMap;
}


[java]
//构造方法注入
public HelloServiceImpl(String greetting,Map typeMap){
this.greetting = greetting;
this.typeMap = typeMap;
System.out.println("call HelloServiceImpl constructor" + this.greetting);
}

//构造方法注入
public HelloServiceImpl(String greetting,Map typeMap){
this.greetting = greetting;
this.typeMap = typeMap;
System.out.println("call HelloServiceImpl constructor" + this.greetting);
} [java] view plaincopyprint


COO


CFO


CEO





COO


CFO


CEO


今天在整一个spring的ioc学习demo,碰到一个问题,居然@Autowire在set方法注入map时,map的key类型不能为String之外的其他类型,具体看下面问题

[java]
@Autowired
public void setTypeMap(Map typeMap) {
this.typeMap = typeMap;
}

@Autowired
public void setTypeMap(Map typeMap) {
this.typeMap = typeMap;
}

xml注入配置,即时在map上加上key和value的类型也不行。

[java]
property name="typeMap">


COO)


CFO


CEO





COO)


CFO


CEO


报错:

[java]
aused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springweb.service.impl.HelloServiceImpl.setTypeMap(java.util.Map); nested exception is org.springframework.beans.FatalBeanException: Key type [class java.lang.Integer] of map [java.util.Map] must be assignable to [java.lang.String]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
at org.springframework.beans.factory.annotation.InjectionMetad