在 MapStruct 中使用的自定义 setter

Custom setter to be used in MapStruct

我一直在浏览 MapStruct documentation 但没有成功。

我正在我的域 classes 和我的 DTO classes 之间实现映射;使用 MapStruct。在我的域中,我不想在我的字段中使用 Setters,因为我们知道今天 Setter 很糟糕(出于很多原因,但这不是我的问题的主题)。

然而,当我想将 ItemDto 转换为 Item 时,我收到以下消息:

Error:(17, 21) java: Property "name" has no write accessor in my.example.Item.

但是我的 class Item 有一个业务方法 void changeName(String newName) 我想在我的 Mapper 中使用。

我的 Mapper 代码是:

@Mapper
public interface MyMapper {

    @Mapping(source="nameDto", target = "name")
    Item map(ItemDto dto);
}

我的问题很简单:如何指定 StructMap 使用 changeName 作为写访问器?

感谢您的帮助。

为了实现类似的功能,您必须编写自己的自定义 AccessorNamingStrategy

如果您的域对象遵循相同的模式changeXXX,那么一个简单的实现可能如下所示:

public class CustomAccessorNamingStrategy extends DefaultAccessorNamingStrategy {


    @Override
    public boolean isSetterMethod(ExecutableElement method) {
        String methodName = method.getSimpleName().toString();
        return methodName.startsWith( "change" ) && methodName.length() > 6;
    }

    @Override
    public String getPropertyName(ExecutableElement getterOrSetterMethod) {
        String methodName = getterOrSetterMethod.getSimpleName().toString();
        if ( methodName.startsWith( "change") {
            return IntrospectorUtils.decapitalize( methodName.substring( 6 );
        }
        return super.getPropertyName( getterOrSetterMethod );
    }
}

您当然可以调整 CustomAccessorNamingStrategy 以满足您的需要。请记住,这将用于所有对象。还有 ItemDto.

有关它的更多信息,请参阅 here MapStruct 文档。