Master MapStruct: Powerful Java Object Mapping for Spring Boot Projects

This guide introduces MapStruct, a Java annotation‑based mapper that outperforms BeanUtils by providing fast, type‑safe conversions between PO, VO, DTO and nested objects, supporting collections, custom logic, dependency injection, constants, expressions, and exception handling within Spring Boot applications.

macrozheng
macrozheng
macrozheng
Master MapStruct: Powerful Java Object Mapping for Spring Boot Projects

About BeanUtils

Using Hutool's BeanUtil for object conversion is common, but it has drawbacks: reflection‑based mapping is slow, it cannot handle different field names or types without manual getters/setters, nested objects require extra code, and collections need explicit loops.

MapStruct Overview

MapStruct is a Java annotation‑based mapper with over 7.5k stars on GitHub. By defining mapping rules in interfaces, it generates implementation classes at compile time, avoiding reflection and delivering excellent performance for simple and complex mappings.

IDEA Plugin Support

MapStruct offers a dedicated IDEA plugin; install it before using the tool.

Project Integration

Add the following Maven dependencies to a Spring Boot project (version 1.6.3):

<dependency>
  <!-- MapStruct core -->
  <groupId>org.mapstruct</groupId>
  <artifactId>mapstruct</artifactId>
  <version>${mapstruct.version}</version>
</dependency>
<dependency>
  <groupId>org.mapstruct</groupId>
  <artifactId>mapstruct-processor</artifactId>
  <version>${mapstruct.version}</version>
  <scope>compile</scope>
</dependency>

Basic Usage

After integrating MapStruct, try its basic features.

Simple Mapping

Define a Member PO class.

Define a MemberDto with some fields renamed or typed differently.

Create a MemberMapper interface with @Mapper and @Mapping annotations to map fields, then obtain an instance via MemberMapper.INSTANCE.

Expose a REST endpoint that converts a Member to MemberDto and returns the result.

Collection Mapping

MapStruct can map a list of PO objects to a list of DTOs automatically.

Add a toDtoList method in the mapper interface.

Test the endpoint; the list conversion works without manual loops.

Nested Object Mapping

MapStruct also supports mapping of nested objects.

Define Order containing Member and Product.

Define OrderDto with MemberDto and List<ProductDto>.

Use @Mapper(uses = {MemberMapper, ProductMapper}) and appropriate @Mapping annotations to map nested fields.

Expose an endpoint to test the nested conversion.

Merge Mapping

MapStruct can merge fields from multiple source objects into a single target.

Create MemberOrderDto extending MemberDto and add order‑specific fields.

Define a method toMemberOrderDto(Member member, Order order) with qualified source properties to avoid conflicts.

Test the composite mapping via a controller endpoint.

Advanced Features

Beyond basic mapping, MapStruct offers dependency injection, constants, default values, expressions, custom pre/post processing, and exception handling.

Dependency Injection

Set componentModel = "spring" on @Mapper to let Spring manage the mapper as a bean.

Inject the mapper with @Autowired in a controller.

Constants, Default Values, Expressions

Use constant to set a fixed value, defaultValue for a fallback, and expression to compute a value (e.g., UUID).

Define a ProductMapper demonstrating these features and test via an endpoint.

Custom Pre‑ and Post‑Mapping

MapStruct allows custom logic before and after mapping, similar to AOP.

Create an abstract mapper class with @BeforeMapping and @AfterMapping methods.

In beforeMapping, clamp negative prices to zero; in afterMapping, set the current time as createTime.

Test the custom processing through a controller endpoint.

Exception Handling

Mapping methods can declare checked exceptions.

Create a custom ProductValidatorException and a validator that throws it when price < 0.

Reference the validator via uses in the mapper and declare throws ProductValidatorException on the mapping method.

Handle the exception in a controller and observe the error logging.

Conclusion

MapStruct provides a powerful, compile‑time alternative to BeanUtils for object mapping in Java backend projects, supporting simple, collection, nested, and merged mappings, as well as advanced features like DI, constants, custom processing, and exception handling.

Project Links

MapStruct repository: https://github.com/mapstruct/mapstruct

Example source code: https://github.com/macrozheng/spring-examples/tree/master/spring-mapstruct

MapStruct illustration
MapStruct illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

dtomapstructObject Mappingmapperspring-boot
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.