在Spring中使用EnumMap

在一个项目中需要使用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"取代。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值