我有個問題。你知道我怎樣才能在不同的通用屬性實作中使用相同的欄位。
我有一個 modelMapper 介面,我用它來概括將被映射的物件的型別
public interface IMapper<S, D> {
D map(S src, Class destination);
}
我也有這個介面的這個實作:
@Component
public class ModelMapperImpl<S,D> implements IMapper<S,D> {
@Autowired
private ModelMapper mapper;
@Override
public D map(S src, Class destination) {
return (D) mapper.map(src, destination);
}
}
問題是這樣的,我需要在我的類中為每個映射一個欄位,我認為這不是一個好習慣,我正在搜索是否有一種方法可以讓我的所有型別的映射只有一個通用欄位
@Service
public class UserService {
private IMapper<AddressDTO, Address> mapperAddress;
private IMapper<UsersDTO, Users> mapperUser; // i want to have only one IMapper field
有沒有辦法做到這一點?謝謝你們的幫助。
uj5u.com熱心網友回復:
我假設您正在嘗試使更改映射庫變得容易(如果需要,從 ModelMapper 移動到其他東西)。然后你可以使方法通用,而不是類。
public interface IMapper {
<S, D> D map(S src, Class<D> destination);
}
實施:
@Component
public class ModelMapperImpl implements IMapper {
@Autowired
private ModelMapper mapper;
@Override
public <S, D> D map(S src, Class<D> destinationClass) {
return mapper.map(src, destinationClass);
}
}
現在您只需要一個IMapper為您服務。
@Service
public class UserService {
@Autowired
private IMapper mapper;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486343.html
上一篇:如何將Mono<ResponseEntity<Object>>轉換為Mono<ResponseEntity<Void>>
