Ask Your Question
3

How can Mapstruct be integrated with Webflux in a springboot application?

asked 2023-02-03 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-06-16 23:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-03 11:00:00 +0000

Seen: 15 times

Last updated: Jun 16 '21