I am writing a mapper with basic dto
-> entity
and vice versa. For a specific field, response
, I need to invoke Gson's toJson()
and fromJson()
methods. By using an expression I was able to generate the needed code in the impl class. However I can't find a way to 'tell' mapstruct to inject the bean I need.
Sample code :
@Mapper(componentModel = SPRING, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface ConfigurationMapper {
@Mapping(target = "response", expression = "java(gson.toJson(configurationDTO.getResponse()))")
MockConfiguration toEntity(ConfigurationDTO configurationDTO);
@Mapping(target = "response", expression = "java(gson.fromJson(configuration.getResponse(),Object.class))")
ConfigurationDTO toDTO(MockConfiguration configuration);
List<ConfigurationDTO> toDTOList(Collection<MockConfiguration> configurations);
}
The Gson config
@Configuration
public class MapperConfiguration {
@Bean
public Gson gson() {
return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssz").registerTypeAdapter(LocalDateTime.class, new LocalDateAdapter())
.create();
}
}
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 11.0.17 (Amazon.com Inc.)"
)
@Component
public class ConfigurationMapperImpl implements ConfigurationMapper {
// I want this to be generated here
@Autowired
Gson gson;
//
@Override
public MockConfiguration toEntity(ConfigurationDTO configurationDTO) {
if ( configurationDTO == null ) {
return null;
}
MockConfiguration mockConfiguration = new MockConfiguration();
mockConfiguration.setId( configurationDTO.getId() );
mockConfiguration.setPath( configurationDTO.getPath() );
mockConfiguration.setStatusCode( configurationDTO.getStatusCode() );
mockConfiguration.setMethod( configurationDTO.getMethod() );
mockConfiguration.setResponse( gson.toJson(configurationDTO.getResponse()) );
return mockConfiguration;
}
.
.
.
}
Any ideas? Don't mind the InjectionStrategy
etc in my Mapper
, I was trying things that maybe would generate the injection I needed.