Mapstruct: Constant values in @Mapping defaultValue with Spring @Value annotation

Created on 16 Aug 2017  路  3Comments  路  Source: mapstruct/mapstruct

Do you have any idea how to achieve constant default value in @Mapping annotation in clean way?

@Value("${default.image.url}")
private final String DEFAULT_USER_IMAGE;

@Mappings({
@Mapping(target = "imageUrl", source = "profileImageUrl", defaultValue = DEFAULT_USER_IMAGE),
@Mapping(target = "balance", defaultValue = "0")
})
public abstract PlayerSummary toSummary(Player source);

Right now my idea is to create @AfterMapping method and then set default value but I think we can improve that. I was also thinking about injection by constructor but... @Value field cannot be static 馃

Most helpful comment

Here is the easy and simple fix

   @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
   public abstract class ValueInjectionMapper {

       @Value("${countryCode}")
       public String countryCode;

       @Mapping(target = "countryCode", expression = "java(getCountryCode())")
       @Mapping(target = "type", constant = "01")
       @Mapping(target = "address", source = "addressInfo")
       public abstract RequestDTO requestInfoToRequestDTO(RequestInfo requestInfo);

       protected String getCountryCode(){
            return countrycode;
       }
    }

All 3 comments

@jpomykala right now there is no other way to do it, apart via @AfterMapping. Unfortunately, annotations can only reference static fields.

What you could use is a custom method that would do the mapping between imageUrl and profileImageUrl. You can select this method by using qualifiers. Have a look more here in the documentation.

I am inclined to close this issue, as there is nothing that we could do at the moment to make this possible in the way you are looking for. If you have some ideas feel free to share them 馃槃

@jpomykala I am going to close this issue for now. If you have some ideas about how to solve this we can reopen the issue.

Here is the easy and simple fix

   @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
   public abstract class ValueInjectionMapper {

       @Value("${countryCode}")
       public String countryCode;

       @Mapping(target = "countryCode", expression = "java(getCountryCode())")
       @Mapping(target = "type", constant = "01")
       @Mapping(target = "address", source = "addressInfo")
       public abstract RequestDTO requestInfoToRequestDTO(RequestInfo requestInfo);

       protected String getCountryCode(){
            return countrycode;
       }
    }
Was this page helpful?
0 / 5 - 0 ratings