"BAEL-3407: Add examples for injecting Spring components in MapStruct" (#10778)

Co-authored-by: Krzysztof Woyke <krzysztof.woyke.sp@lhsystems.com>
This commit is contained in:
kwoyke 2021-05-21 07:16:08 +02:00 committed by GitHub
parent 8f2208fb25
commit 31f40d8623
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.baeldung.mapper;
import com.baeldung.dto.SimpleSource;
import com.baeldung.entity.SimpleDestination;
import com.baeldung.service.SimpleService;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.beans.factory.annotation.Autowired;
@Mapper(componentModel = "spring")
public abstract class SimpleDestinationMapperUsingInjectedService {
@Autowired
protected SimpleService simpleService;
@Mapping(target = "name", expression = "java(simpleService.enrichName(source.getName()))")
public abstract SimpleDestination sourceToDestination(SimpleSource source);
public abstract SimpleSource destinationToSource(SimpleDestination destination);
}

View File

@ -0,0 +1,11 @@
package com.baeldung.service;
import org.springframework.stereotype.Service;
@Service
public class SimpleService {
public String enrichName(String name) {
return "-:: " + name + " ::-";
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.mapper;
import com.baeldung.dto.SimpleSource;
import com.baeldung.entity.SimpleDestination;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SimpleDestinationMapperUsingInjectedIntegrationTest {
@Autowired
private SimpleDestinationMapperUsingInjectedService mapper;
@Test
public void givenSourceToDestination_whenMaps_thenNameEnriched() {
// Given
SimpleSource source = new SimpleSource();
source.setName("Bob");
source.setDescription("The Builder");
// When
SimpleDestination destination = mapper.sourceToDestination(source);
// Then
assertThat(destination).isNotNull();
assertThat(destination.getName()).isEqualTo("-:: Bob ::-");
assertThat(destination.getDescription()).isEqualTo("The Builder");
}
}