现在的位置: 首页 > 综合 > 正文

在Spring中使用EnumMap

2013年10月16日 ⁄ 综合 ⁄ 共 1791字 ⁄ 字号 评论关闭
在一个项目中需要使用Enum类型,并且使用EnumMap做枚举值和值得含义间的映射,同时使用Spring做Ioc,开始的时候不得要领,搜索到这个后才可以,过程记录如下。

1.创建Enum类型的对象,例如:
public enum ServiceReturnCode {
    Success,
    Fail,
    Unavailable,
    ;          
}

2.为其他需要使用枚举映射的类加入EnumMap类型的属性,并指定泛型,例如:
public class Obj{
    ....;
    // 声明一个从 ServiceReturnCode 类型到 String 类型的枚举映射。
    private EnumMap<ServiceReturnCode, String> returnCodeMap;
}

3.为 returnCodeMap 属性加入getter和setter方法。
注意getter和setter要操作Map接口而不是默认的EnumMap,另外在setter中要根据传入的Map的实例创建一个EnumMap。如果使用ide自动建立getter和setter,请修改到如下的样子:
public Map<ServiceReturnCode, String> getReturnCodeMap() {
    return this.returnCodeMap;
}

public void setReturnCodeMap(Map<ServiceReturnCode, String> returnCodeMap) {
    this.returnCodeMap = new EnumMap<ServiceReturnCode, String>(returnCodeMap);
}

4.编写Spring的配置文件。
Spring要使用2.0以上版本的,因为要使用命名空间。示例配置如下:
<?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-2.5.xsd
 http://www.springframework.org/schema/util
 http://www.springframework.org/schema/util/spring-util-2.5.xsd"> 

    ....other beans....
    <util:map id="codeMap" key-type="examples.ServiceReturnCode">
        <entry key="Success" value="服务成功"/>
        <entry key="Fail" value="服务失败"/>
        <entry key="Unavailable" value="服务不可用"/>
    </util:map>

    <bean id="demoObj" class="examples.Obj"
        ....other propertes injection....
        <property name="returnCodeMap">
            <ref bean="codeMap"/>
        </property>
    </bean>
</beans>
使用util:map去实例化一个LinkedHashMap类型的bean,而不是缺省的map;更重要的是,可以指定泛型中的Key的类型为你需要的枚举类型。

另外由于使用了Spring2.0框架,需要注意她和1.x的一些区别,例如使用xsd验证而不是dtd,还有 singleton="true/false" 的用法已废弃,以 scope="singleton/prototype"取代。

抱歉!评论已关闭.