MapStruct

一、前言

       MapStruct是一个基于注解(jdk6 annotation processor, 例如 lombok)的代码生成框架,用于实现不同对象之间的映射。

二、使用样例

1.用于映射的样例

public class Customer {

    private Long id;
    private String name;

    //getters and setter omitted for brevity
}

public class CustomerDto {

    public Long id;
    public String customerName;
}

@Mapper
public interface CustomerMapper {

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

    @Mapping(source = "customerName", target = "name")
    Customer toCustomer(CustomerDto customerDto);

    @InheritInverseConfiguration
    CustomerDto fromCustomer(Customer customer);
}

2.使用转化器

@Service
public class CustomerService{
    @Resource
    private CustomerRepository repository;
    
    /**
    * 存储顾客
    */
    public void saveCustomer(CustomerDto dto){
        Customer customer =  CustomerMapper.INSTANCE.toCustomer(dto);
        repository.save(customer);
    }
}

三、高级扩展

1.请求驼峰处理器

a.实现自定义命名插件

将target的setter和getter方法与source的property对应

public class CustomCamelNamingStrategy extends DefaultAccessorNamingStrategy {


    @Override
    public String getPropertyName(ExecutableElement getterOrSetterMethod) {
        String methodName = getterOrSetterMethod.getSimpleName().toString();
        if (methodName.contains("-")){
            String fieldName = methodName.subString(3);
            char []chs = fieldName.toCharArray();
            chs[0] =  Character.toLowerCase(chs[0]);
            return toCamelName(new String(chs));
        }
        return super.getPropertyName(getterOrSetterMethod);
    }

    private String toCamelName(String fieldName){
        String res = "";
        char[] chs = fieldName.toCharArray();
        for (int i = 0; i < chs.length; i++){
            if(chs[i] == '_'){
                res += Character.toUpperCase(chs[++i]); 
                continue;
            }
            res+=chs[i];
        }
        return res;
    }
}

b.配置使用

java spi 配置

resources/META-INF.services/org.mapstruct.ap.spi.AccessorNamingStrategy

org.mapstruct.example.spi.CustomCamelNamingStrategy 

你可能感兴趣的:(基础服务,java)