Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Mapstruct can be integrated with Webflux in a Spring Boot application by following these steps:

  1. Add the mapstruct and mapstruct-processor dependencies to the pom.xml file.
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.4.2.Final</version>
</dependency>

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.4.2.Final</version>
    <scope>provided</scope>
</dependency>
  1. Create the mapping interface with the required mappings.
@Mapper
public interface PersonMapper {
    PersonDto toDto(Person person);
    Person toEntity(PersonDto personDto);
}
  1. Add the @MapperComponentModel annotation to the mapping interface to enable Spring component model.
@MapperComponentModel("spring")
public interface PersonMapper {
    PersonDto toDto(Person person);
    Person toEntity(PersonDto personDto);
}
  1. Inject the mapping interface in the Webflux controller.
@RestController
@RequestMapping("/api")
public class PersonController {

    private final PersonMapper personMapper;

    @Autowired
    public PersonController(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    @GetMapping("/person/{id}")
    public Mono<PersonDto> getPerson(@PathVariable String id) {
        return personRepository.findById(id)
            .map(personMapper::toDto);
    }

    @PostMapping("/person")
    public Mono<Void> createPerson(@RequestBody Mono<PersonDto> personDtoMono) {
        return personDtoMono
            .map(personMapper::toEntity)
            .flatMap(personRepository::save)
            .then();
    }
}
  1. Enable mapstruct in the project by adding the org.mapstruct.spring.mapstruct-spring-boot-starter dependency.
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-spring-boot-starter</artifactId>
    <version>1.4.2.Final</version>
</dependency>
  1. Run the Spring Boot application and test the endpoints.

By following these steps, Mapstruct can be integrated with Webflux in a Spring Boot application.