Mapstruct-字符串操作,但仅针对一个属性



我不确定这里缺少什么。我的自定义逻辑应用于所有的String属性,而不是我为target指定的一个。

@ApiModel(value="ShopProduct")
@Data
public class ShopProductDTO {
private String description;
private String fullImagePath;
}
@Entity
@Table(name = "shop_product")
public class ShopProduct implements Serializable {
@Column(name = "desc")
private String description;
@Column(name = "thumb_path")
private String thumbPath;
//getters,setters

ImageMapper:

@Component
public class ImagePathMapper {
AppConfig appConfig;
public ImagePathMapper(AppConfig appConfig) {
this.appConfig = appConfig;
}
public String toFullImagePath(String thumbPath){
return appConfig.getImagePath() + thumbPath;
}
}

商店产品映射器:

@Mapper(componentModel = "spring", uses = {ImagePathMapper.class})
@Component
public interface ShopProductMapper {
@Mapping(target = "fullImagePath", source = "thumbPath")
ShopProductDTO shopProductToShopProductDTO(ShopProduct shopProduct);
}

生成的mapstruct类:

ShopProductDTO shopProductDTO = new ShopProductDTO();
shopProductDTO.setDescription( imagePathMapper.toFullImagePath( shopProduct.getName() ) );
shopProductDTO.setFullImagePath( imagePathMapper.toFullImagePath( shopProduct.getThumbPath() ) );
}

为什么描述字段也与toFullImagePath一起使用?

这难道不应该@映射(目标="fullImagePath",源="thumbPath"(;指定仅更改fullImagePath?

这不是它的工作方式。

定义映射时,Mapstruct将尝试主要基于属性名称约定将源对象中的每个属性映射到目标对象。

当您定义@Mapping注释时,您指示该基本映射的异常

在您的示例中,当您定义以下内容时:

@Mapping(target = "fullImagePath", source = "thumbPath")

您指示源对象中的属性thumbPath应映射到目标对象中的fullImagePath:这是必要的,因为它们具有不同的名称,否则映射将不会成功。

另一方面,当您定义uses=ImagePathMapper.class属性时,您正在指示Mapstruct转换在源对象中找到的定义为某个Class类型(在本例中为String(的每个属性:只要ShopProduct中定义的所有字段都是String,则此映射器将应用于每个属性。

如果您只想将映射器应用于一个字段,则可以调用自定义映射方法,或使用装饰器,或前后映射注释,如以下示例所示:

@Mapper(componentModel = "spring", uses=AppConfig.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public abstract class ShopProductMapper {
abstract ShopProductDTO shopProductToShopProductDTO(ShopProduct shopProduct);
@Autowired
public void setAppConfig(AppConfig appConfig) {
this.appConfig = appConfig;
}
@AfterMapping
public void toFullImagePath(@MappingTarget ShopProductDTO shopProductDTO, ShopProduct shopProduct) {
String thumbPath = shopProduct.getThumbPath();
if (thumbPath != null) {
shopProductDTO.setFullImagePath(appConfig.getImagePath() + thumbPath);
}
}
}

请注意,在该示例中,您需要对映射器进行几次更改才能正确使用Spring:请参阅此和此。

相关内容

  • 没有找到相关文章

最新更新