spring @Autowired map

 注入map,日常通常不會這麼作,今天在寫一個demo時,有以下一段注入代碼:java

map bean 的建立spring

@Bean(name="userMap")
public Map<Long, User> userMap() {
    return new ConcurrentHashMap<Long, User>();
}
// 注入
@Autowired
@Qualifier("userMap")
private Map<Long, User> userMap;

怕出錯,我還特地加了Qualifier限定符,可是spring 容器就起不來了,異常以下,大概意思就是map的key要是String類型才行:ui

Caused by: org.springframework.beans.FatalBeanException: Key type [class java.lang.Long] of map [java.util.Map] must be assignable to [java.lang.String]spa

緣由以下:org.springframework.beans.factory.support.DefaultListableBeanFactory中的一段代碼code

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;
            }


用set 方法也不行。可是使用以下方法卻奏效了:ip

@Resource(name = "userMap")
private Map<Long, User> userMap;
相關文章
相關標籤/搜索