且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用MapStruct 1.2有条件地映射属性?

更新时间:2022-02-18 08:52:30

使用MapStruct不能真正做到这一点. @ValueMapping 批注用于映射 Enum .

You can't really do that with MapStruct. The @ValueMapping annotation is for mapping of Enum(s).

要实现所需的功能,您需要在 @BeforeMapping @AfterMapping 中进行操作.

In order to achieve what you are looking for you would need to do that in @BeforeMapping or @AfterMapping.

例如,您可以执行以下操作:

For example you can do something like:

@Mapper
public interface JiraKpmMapper {

    @BeforeMapping
    default void beforeMapping(@MappingTarget MyTarget target, MySource source) {
        if (source.getPropY().equals("ABC") {
            target.setPropX("V01.123.456.AB");
        }
    }

    @Mapping(target = "propX", ignore = true) // This is now mapped in beforeMapping
    MyTarget source2Target(final MySource mySource);
}

您的自定义映射器应该具有一个 @AfterMapping .将 propX 转换为类的位置.您甚至可以将其作为我编写的 @BeforeMapping 的一部分并直接创建您的类(或调用将从 String 转换为类的方法)

Your custom mapper then should have an @AfterMapping. Where you would convert the propX into your class. You can even do this as part of the @BeforeMapping I wrote and directly create your class (or invoke the method that does the conversion from String into a class)