mapstruct的用法之qualifiedByName示例詳解
qualifiedByName的意思就是使用這個Mapper接口中的指定的默認方法去處理這個屬性的轉換,而不是簡單的get set。網上一直沒找到…
可用于格式化小數位等,在po轉換為vo時就已格式化小數位完成,所以不必單獨再寫代碼處理小數位。
1 引用pom1 ,能正常使用mapstruct的注解,但不會生成Impl類
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.Final</version>
</dependency>引用pom2 才會生成Impl類
2 定義ConvertMapper
package com.weather.weatherexpert.common.model.mapper;
import com.weather.weatherexpert.common.model.po.AreaPO;
import com.weather.weatherexpert.common.model.vo.AreaVO;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;
import java.text.DecimalFormat;
/**
* <p>Title: </p>
* <p>Description: </p>
*
*/
@Mapper
public interface ConvertMapper {
ConvertMapper INSTANCE = Mappers.getMapper(ConvertMapper.class);
@Mapping(source = "pm25", target = "pm25", qualifiedByName = "formatDoubleDef")
AreaVO areaPO2areaVO(AreaPO areaPO);
@Named("formatDoubleDef")//需要起個名字,不然報錯,可以與方法名一致,當然也可以不一致
default Double formatDouble(Double source) {
DecimalFormat decimalFormat = new DecimalFormat("0.00");//小數位格式化
if (source == null) {
source = 0.0;
}
return Double.parseDouble(decimalFormat.format(source));
}
}
3 定義源類和目標類
public class AreaPO {
private String cityName;
private Integer haveAir;
private Double pm25;
private String pm10Str;
............
}
public class AreaVO {
private String cityName;
private Integer haveAir;
private Double pm25;
private String pm25Str;
private Double pm10;
......
}
4 看生成的Impl類ConvertMapperImpl
package com.weather.weatherexpert.common.model.mapper;
import com.weather.weatherexpert.common.model.po.AreaPO;
import com.weather.weatherexpert.common.model.vo.AreaVO;
public class ConvertMapperImpl implements ConvertMapper {
public ConvertMapperImpl() {
}
public AreaVO areaPO2areaVO(AreaPO areaPO) {
if (areaPO == null) {
return null;
} else {
AreaVO areaVO = new AreaVO();
areaVO.setPm25(this.formatDouble(areaPO.getPm25()));
areaVO.setCityName(areaPO.getCityName());
areaVO.setHaveAir(areaPO.getHaveAir());
return areaVO;
}
}
5 測試
AreaPO areaPO = new AreaPO("忻州", 1, 1.256879);
AreaVO areaVO =
ConvertMapper.INSTANCE.areaPO2areaVO(areaPO);
logger.info("JSON.toJSONString(areaVO):" + JSON.toJSONString(areaVO));
輸出:
JSON.toJSONString(areaVO):{“cityName”:“忻州”,“haveAir”:1,“pm25”:1.26}
關于@Target注解的使用可見:
詳解JDK 5 Annotation 注解之@Target的用法介紹
到此這篇關于mapstruct的用法之qualifiedByName示例詳解的文章就介紹到這了,更多相關mapstruct的用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring boot通過切面,實現超靈活的注解式數據校驗過程
這篇文章主要介紹了Spring boot通過切面,實現超靈活的注解式數據校驗過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
springboot 自定義異常并捕獲異常返給前端的實現代碼
在開發(fā)中,如果用try catch的方式,每個方法都需要單獨實現,為了方便分類異常,返回給前端,采用了@ControllerAdvice注解和繼承了RuntimeException的方式來實現,具體實現內容跟隨小編一起看看吧2021-11-11

