Created
June 16, 2021 14:02
-
-
Save robsonkades/b85e19c5c6b8e413948dda5a2eeca817 to your computer and use it in GitHub Desktop.
ModelMapperConfiguration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.kades.robson.configuration; | |
import java.util.HashSet; | |
import java.util.Set; | |
import org.modelmapper.ModelMapper; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import lombok.AccessLevel; | |
import lombok.experimental.FieldDefaults; | |
@Configuration | |
public class ModelMapperConfiguration { | |
@Bean | |
public CustomModelMapper modelMapper() { | |
CustomModelMapper modelMapper = new CustomModelMapper(); | |
modelMapper.getConfiguration().setFieldMatchingEnabled(true) // | |
.setAmbiguityIgnored(true); | |
return modelMapper; | |
} | |
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) | |
public static class CustomModelMapper extends ModelMapper { | |
Set<Class<?>> allowedNullSources = new HashSet<>(); | |
@Override | |
public <D> D map(Object source, Class<D> destinationType) { | |
if (source == null && allowedNullSources.contains(destinationType)) { | |
source = new Object(); | |
} | |
return super.map(source, destinationType); | |
} | |
void allowNullSources(Class<?> destinationType) { | |
allowedNullSources.add(destinationType); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment