Is there a global setting in Mapstruct that will trim a string value prior to setting it to a destination bean property
Asked Answered
P

2

13

Is it possible to trim a string value before it is set against a bean property of type string in the destination bean?

Dozer offers such a facility through its mapping configuration for example,

<configuration>
    <trim-strings>true</trim-strings>
</configuration>

Also see Dozer Global Configuration

With MapStruct 1.0.0.Final I can achieve this through Expressions or Before/After Mapping customization.

But wanted to know if there is a better way to handle such use cases.

Thanks in advance.

Provincialism answered 1/8, 2016 at 16:2 Comment(0)
P
4

It appears MapStruct in its current form does not support this.

However one can achieve this effect with custom mapper methods, for example implement a class with a method that trims a String argument passed to it and then reference this class in the use attribute of the @Mapper annotation. More at Invoking other mappers

If you require fine gained access control you could use Selection based on Qualifiers

I was made aware of these approaches in response to a question I posted in mapstruct Google group

Provincialism answered 2/8, 2016 at 14:31 Comment(0)
H
3

Example from @venkat-srinivasan answer's:

public class StringTrimmer {

   public String trimString(String value) {
      return value.trim();
   }
}

and then in your mapper interface or class:

@Mapper(uses = StringTrimmer.class)
   public interface MyMapper {
Hunsaker answered 10/11, 2022 at 7:41 Comment(1)
return value != null ? value.trim() : null;Goliard

© 2022 - 2024 — McMap. All rights reserved.