源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

详解SpringMVC 自动封装枚举类的方法

  • 时间:2022-11-16 21:26 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:详解SpringMVC 自动封装枚举类的方法
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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部