?场景
前台提交到后台的数据使用一个实体类进行封装,需要将总实体类的数据放到不同的实体类中.一般会在业务层像下面这么写
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(jtv010Form, userEntity);
PersonEntity personEntity = new PersonEntity();
BeanUtils.copyProperties(jtv010Form, personEntity);
能实现功能,但是语义化不好,可读性低
😁语义化较好的书写方法
?前台提交的表单Bean
import org.springframework.beans.BeanUtils;
public class Jtv010Form {
private String id;
private String name;
private String age;
private String address;
private String hobby;
public UserEntity convertToUserEntity(){
Jtv010FormToUserConverter toUserConverter = new Jtv010FormToUserConverter();
return toUserConverter.convert(this);
}
public PersonEntity convertToPersonEntity(){
Jtv010FormToPersonConverter toPersonConverter = new Jtv010FormToPersonConverter();
return toPersonConverter.convert(this);
}
private static class Jtv010FormToUserConverter implements FormConvert<Jtv010Form, UserEntity> {
@Override
public UserEntity convert(Jtv010Form jtv010Form) {
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(jtv010Form, userEntity);
return userEntity;
}
}
private static class Jtv010FormToPersonConverter implements FormConvert<Jtv010Form, PersonEntity> {
@Override
public PersonEntity convert(Jtv010Form jtv010Form) {
PersonEntity personEntity = new PersonEntity();
BeanUtils.copyProperties(jtv010Form, personEntity);
return personEntity;
}
}
}
?实体类转换接口
public interface FormConvert<S,T> {
T convert(S s);
}
?待转换的实体类
public class UserEntity {
private String id;
private String name;
private String age;
}
public class PersonEntity {
private String id;
private String address;
private String hobby;
}
?测试
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Test3 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
Jtv010Form jtv010Form = new Jtv010Form();
jtv010Form.setId("1");
jtv010Form.setName("贾飞天");
jtv010Form.setAge("18");
jtv010Form.setAddress("地球");
jtv010Form.setHobby("喝水");
UserEntity userEntity = jtv010Form.convertToUserEntity();
System.out.println(userEntity);
PersonEntity personEntity = jtv010Form.convertToPersonEntity();
System.out.println(personEntity);
}
}
|