Я использую Springboot v 2.3.2.
У меня другой класс сущности, например A и B. Теперь после выполнения операций CRUD мне нужно возвращать ответы в формате HAL. В настоящее время я создал методы в каждом классе контроллера. Но со временем я вижу, что они похожи по своей природе. Поэтому я думаю о его рефакторинге и применении Java Generics.
Вот фрагмент кода. Пожалуйста, расскажите, как я могу внести это изменение, или есть другой способ лучше.
В обоих этих методах, кроме типа сущности, все одинаково.
import org.springframework.hateoas.EntityModel;
private final RepositoryEntityLinks entityLinks;
private EntityModel<A> generateLinks(A a) {
EntityModel<A> resource = EntityModel.of(a);
resource.add(entityLinks.linkToItemResource(A.class, a.getId()).withSelfRel());
resource.add(entityLinks.linkToCollectionResource(A.class));
resource.add(entityLinks.linksToSearchResources(A.class));
return resource;
}
private EntityModel<B> generateLinks(B b) {
EntityModel<B> resource = EntityModel.of(b);
resource.add(entityLinks.linkToItemResource(B.class, b.getId()).withSelfRel());
resource.add(entityLinks.linkToCollectionResource(B.class));
resource.add(entityLinks.linksToSearchResources(B.class));
return resource;
}
Вот способ добиться этого.
public <T> EntityModel<T> generateLinks(T entity, Object id) {
EntityModel<T> resource = EntityModel.of(entity);
resource.add(entityLinks.linkToItemResource(entity.getClass(), id).withSelfRel());
resource.add(entityLinks.linkToCollectionResource(entity.getClass()));
resource.add(entityLinks.linksToSearchResources(entity.getClass()));
return resource;
}