MapStruct文档(十一)——SPI

  • Post author:
  • Post category:其他


mapstruct提供了一些列SPI,供我们自定义实现一些功能:

AccessorNamingStrategy

(实现自定义的get/set,获取字段名)、

DefaultProvider

(实现自定义的建造者)、

MappingExclusionProvider

(实现自定义的排除,也就是不自动映射字段)、

EnumMappingStrategy

(实现自定义的枚举命名)、

EnumTransformationStrategy

(实现自定义的枚举转换)。

要实现自定义功能要先建一个项目,可以打包成jar包,自定义的实现以上接口,在resources包下新建META-INF.services包,再新建一个文件,文件名是被继承的类的全路径(都是在org.mapstruct.ap.spi包下),文件内容为自定义类的全路径;然后在使用到的项目中的pom文件的build->plugins->configuration->annotationProcessorPaths->mapstruct-processor的path后添加一个上述新建的项目的path标签。


public class CustomEnumTransformationStrategy implements EnumTransformationStrategy {

    @Override
    public String getStrategyName() {
        return "custom";
    }

    @Override
    public String transform(String value, String configuration) {
        return value.toLowerCase() + configuration;
    }
}

org.mapstruct.ap.spi.EnumTransformationStrategy文件内容

com.haru.acfun.CustomEnumTransformationStrategy


public enum LevelEnum {

    ABLE(1, "完美"),
    DISABLE(2, "合格"),
    NORMAL(3, "普通"),
    FAILED(4, "不及格"),
    OK(5, "还行"),
    FINE(6, "可以");

    private Integer code;

    private String desc;

    LevelEnum(Integer code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}


@Mapper
public interface TestMapper {

    @EnumMapping(nameTransformationStrategy = "custom", configuration = "_status")
    DisableStatus toEnum(LevelEnum levelEnum);

}
 
@Component
public class TestMapperImpl implements TestMapper {

    @Override
    public DisableStatus toEnum(LevelEnum levelEnum) {
        if ( levelEnum == null ) {
            return null;
        }

        DisableStatus disableStatus;

        switch ( levelEnum ) {
            case ABLE: disableStatus = DisableStatus.able_status;
            break;
            case DISABLE: disableStatus = DisableStatus.disable_status;
            break;
            case NORMAL: disableStatus = DisableStatus.normal_status;
            break;
            case FAILED: disableStatus = DisableStatus.failed_status;
            break;
            case OK: disableStatus = DisableStatus.ok_status;
            break;
            case FINE: disableStatus = DisableStatus.fine_status;
            break;
            default: throw new IllegalArgumentException( "Unexpected enum constant: " + levelEnum );
        }

        return disableStatus;
    }
}

自定义的枚举转换是将枚举字段值转成小写再加上配置后缀。这样可以正常映射。



版权声明:本文为sinat_32787481原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。