springboot 枚举类的转换(converter)

一、过程

1、前端传入:interage自动转换String类型

2、数据库枚存储举类对应的类型:tinyint

3、流程

请求: 前端传入string类型(code) -> 在controller层接收,转换成枚举类型 ->  转换成数据库类

响应:数据库tinyint -> 枚举类型 -> 前端的interage类型

二、请求过程,string转换枚举类型(难点)

1、前提

抽取枚举接口BaseEnum

a、接口

package com.wt.lease.model.enums;

public interface BaseEnum {

    Integer getCode();

    String getName();
}

b、案例

package com.wt.lease.model.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;


public enum ItemType implements BaseEnum {

    APARTMENT(1, "公寓"),

    ROOM(2, "房间");


    @EnumValue
    @JsonValue
    private Integer code;
    private String name;

    @Override
    public Integer getCode() {
        return code;
    }


    @Override
    public String getName() {
        return name;
    }

    ItemType(Integer code, String name) {
        this.code = code;
        this.name = name;
    }

}

2、创建装换类

package com.wt.lease.web.admin.custom.converter;

import com.wt.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    if (enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("code:" + code + "非法");
            }
        };
    }
}

3、配置转换类

package com.wt.lease.web.admin.custom.config;

import com.wt.lease.web.admin.custom.converter.StringToBaseEnumConverterFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        WebMvcConfigurer.super.addFormatters(registry);
        registry.addConverterFactory(this.stringToBaseEnumConverterFactory);
    }
}

三、请求过程,枚举类型转换 数据库 int类型

在code字段上,添加@EnumValue 注解

@EnumValue
private Integer code;

四、相应过程,枚举类型转换成 int

在code字段,添加@JsonValue注解

@EnumValue
@JsonValue
private Integer code;

 

posted @ 2025-05-10 16:46  市丸银  阅读(189)  评论(0)    收藏  举报