MapStruct 需要 Impl 类

2022-09-02 11:08:24

我有下一个课程:

映射

public interface DeviceTokensMapper {

    DeviceTokensMapper INSTANCE = Mappers.getMapper(DeviceTokensMapper.class);

    @Mappings({
            @Mapping(source = "tokenName", target = "tokenName"),
            @Mapping(source = "userOsType", target = "osType"),
    })

    DeviceTokensDTO toDeviceTokensDTO(DeviceTokens deviceTokens);
}

实体:

@Entity
public class DeviceTokens {

    @Id
    @Column(name="token_name", nullable = false)
    private String tokenName;

    @Column(name = "os", nullable = false)
    @Enumerated
    private UserOSType userOsType;

    public DeviceTokens() {}

    public DeviceTokens(String tokenName, UserOSType userOSType) {
        this.tokenName = tokenName;
        this.userOsType = userOSType;
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }

    public UserOSType getUserOsType() {
        return userOsType;
    }

    public void setUserOsType(UserOSType userOsType) {
        this.userOsType = userOsType;
    }
}

断续器:

public class DeviceTokensDTO {

    private String tokenName;

    private UserOSType osType;

    public DeviceTokensDTO() {}

    public DeviceTokensDTO(String tokenName, UserOSType osType) {
        this.tokenName = tokenName;
        this.osType = osType;
    }

    public UserOSType getOsType() {
        return osType;
    }

    public void setOsType(UserOSType osType) {
        this.osType = osType;
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }
}

和来自 spring 服务类的方法,我使用此映射:

@Transactional
public DeviceTokensDTO storeToken(String tokenId, UserOSType userOsType) {
    DeviceTokens deviceTokens = new DeviceTokens(tokenId, userOsType);
    DeviceTokens newDevice = deviceTokensRepository.save(deviceTokens);

    return DeviceTokensMapper.INSTANCE.toDeviceTokensDTO(newDevice);
}

当我运行上面的方法时,我看到下一个异常:

错误 [调度程序服务器]:?- Servlet.service() for servlet [dispatcherServlet] in context with path [] 抛出异常 [Handler processing failed; nested exception is java.lang.ExceptionInInitializerError] 与 root cause java.lang.ClassNotFoundException: dto.DeviceTokensMapperImpl

那么为什么映射器需要实现类呢?可以请别人建议吗?谢谢。


答案 1

如果使用 maven,则需要添加 mapstruct-processor 依赖项,如下所示:

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-jdk8</artifactId>
    <version>1.2.0.Final</version>
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.2.0.Final</version>
</dependency>

答案 2

MapStruct 在编译时生成代码,调用 to 将查找映射器接口的生成实现。由于某种原因,您的部署单元(WAR等)中似乎缺少它。Mappers.getMapper(DeviceTokensMapper.class);

顺便说一句,当使用Spring作为DI容器时,您可以使用并且您将能够通过依赖注入而不是使用工厂来获取映射器实例。@Mapper(componentModel="spring")Mappers


推荐