cherless2

博客园 首页 新随笔 联系 订阅 管理

springmvc默认无法自动封装枚举类,解决方法如下:

1.枚举类

public enum GoodsPromoteEnum {

    /**
     * 0 精品
     */
    fine("精品",0),
    /**
     * 1 限时购
     */
    limit("限时购",1), 
    /**
     * 2 特价
     */
    cheap("特价",2);
    
    private String value;

    private int index;

    private GoodsPromoteEnum(String value, int index) {
        this.value = value;
        this.index = index;
    }
    
    public  static GoodsPromoteEnum get(String value){
        for (GoodsPromoteEnum p : GoodsPromoteEnum.values()) {
            if (p.getValue().equals(value)) {
                return p;
            }
        }
        return null;
    }
    
    public  static GoodsPromoteEnum get(int index){
        for (GoodsPromoteEnum p : GoodsPromoteEnum.values()) {
            if (p.getIndex() == index) {
                return p;
            }
        }
        return null;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}

2.编写自定义处理类,继承Converter接口

public class StringToGoodsConverter implements Converter<String, GoodsPromoteEnum> {

    @Override
    public GoodsPromoteEnum convert(String value) {
        if (StringUtils.isBlank(value)) {
          return null;
        }
        return GoodsPromoteEnum.get(value);
    }

}

3.在springmvc配置文件里配置

    <!--自定义枚举类封装  -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
          <set>
            <bean class="com.tentcoo.zbh.util.StringToGoodsConverter" />
          </set>
        </property>
      </bean>

 

posted on 2016-06-13 15:00  cherless2  阅读(4071)  评论(0编辑  收藏  举报