background

We generally use ObjectMapper, beanUtils and other objects to copy attributes in Java, which is very convenient, but the underlying logic is used in serialization, reflection and other principles. This is not always as efficient as writing getters/setters by hand. However, the implementation of manual writing getter/setter in the face of large objects with multiple attributes will inevitably appear a little bloated and difficult to maintain, so the protagonist mapStruct is introduced. MapStruct implements object replication through annotation configuration, which is very convenient.Copy the code

use

Pom depends on

< the dependency > < groupId > org. Mapstruct < / groupId > < artifactId > mapstruct < / artifactId > < version > 1.5.0. Walk < / version > </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> < version > 1.5.0. Beta1 < / version > < / dependency >Copy the code

Here’s a quick example:

The first step is to create two objects that need to be copied from each other. The second step is to annotate the method as an object copy method. The third step is the call method;

It’s very clear how he does it. It’s interesting.

The principle of

  1. Annotate that this is a mapStruct class;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface CarMapper {
 

    @Mapping(source = "numberOfSeats", target = "seatCount")
    CarDto carToCarDto(Car car);
}
Copy the code
  1. The implementation class of CarMapper is compiled at compile time, and the object copy method is completely implemented with getter/setter methods.

  1. CarMapperImpl; carMapperImpl;
CarMapper mapper = Mappers.getMapper(CarMapper.class);
Copy the code

How is the implementation class generated?

The answer to this question lies in the mapstruct-processor dependency:

The MAPstucit-Processor uses the SPI mode,

Defined in the meta-inf/services directory javax.mail. Annotation. Processing. The Processor implementation class org. Mapstruct. App. MappingProcessor

According to JSP269 protocol, MappingProcessor implements process method in Processor interface, and generates implementation class of Mapper according to annotation.

JSR269

Introduction to Java dynamic compilation and the JSR269 Plug-in Annotation Processing API (JSR269)