简体   繁体   中英

Mapstruct Mapper Extension

Hi this seems to work for adding extra methods but not for adding new annotations on an existing method. Say that we have the following classes:

public class SourceClass {
    private String field_1;
    private String field_2;
}

public class TargetParent {
    private String field_a;
}

public class TargetChild extends TargetParent {
    private String field_b;
}

The parent object is part of a framework that can extended by other parties. The child object is an example of a concrete extension that adds a new field.

I was planning an approach with Mapping Hierarchy like the following:

@Mapper
public interface ParentMapper {
    @Mapping(source="field_1", target="field_a")
    public TargetParent convert(SourceClass source);
}

@Mapper
public interface ChildMapper extends ParentMapper {
    @Mapping(source="field_2", target="field_b")
    public TargetChild convert(SourceClass source);
}

I was expecting to see the implementation of ChildMapper to have:

public TargetChild convert(SourceClass source){
    // target instanciation through factory here
    target.setField_a(field_1);
    target.setField_b(field_2);
}

But this doesn't work: @Mapping Annotations don't seem to be inherited.

I can try to figure out some alternative solutions, but it seems that I'm starting to hack out the framework, which is not my intension.

Am I missing something here?

If you want to inherit certain annotations they you should use Mapping configuration inheritance .

eg

@Mapper
public interface ParentMapper {
    @Mapping(source="field_1", target="field_a")
    public TargetParent convert(SourceClass source);
}

@Mapper(config = ParentMapper.class)
public interface ChildMapper {
    @Mapping(source="field_2", target="field_b")
    @InheritConfiguration
    public TargetChild convert(SourceClass source);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM