i have a question. do you know how can i use the same field with différent generic attribut implementation.
I have an interface for modelMapper that i am using to generalise the Type of objects that will be mapped
public interface IMapper<S, D> {
D map(S src, Class destination);
}
I also have this implementation of this interface :
@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);
}
}
The problem is this, i need to have for each mapping a field in my class which is not a good practice i think and i am searching if there is a way to have only one generic field for all my type of mappings
@Service
public class UserService {
private IMapper<AddressDTO, Address> mapperAddress;
private IMapper<UsersDTO, Users> mapperUser; // i want to have only one IMapper field
is there is a way to do That ? thank you guys for your help.
CodePudding user response:
I'll assume you are trying to make it easy to change the mapping library(moving from ModelMapper to something else, if it's needed). Then you can make the method generic, not the class.
public interface IMapper {
<S, D> D map(S src, Class<D> destination);
}
Impl:
@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);
}
}
Now you need only one IMapper
in your service.
@Service
public class UserService {
@Autowired
private IMapper mapper;
}