Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save robsonkades/b85e19c5c6b8e413948dda5a2eeca817 to your computer and use it in GitHub Desktop.
Save robsonkades/b85e19c5c6b8e413948dda5a2eeca817 to your computer and use it in GitHub Desktop.
ModelMapperConfiguration
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