如何解决是否有任何替代方法可以重用 RepresentationModelAssemblerSupport
对于每个 Model
类,我必须创建一个 RepresentationModelAssemblerSupport
类,这有点多余,所以我编写了一个通用的 RepresentationModelAssemblerSupport
类。
通用 RepresentationModelAssemblerSupport 类:
public class ModelAssembler<T,E extends RepresentationModel<E>> extends RepresentationModelAssemblerSupport<T,E> {
private final Class<E> model;
public ModelAssembler(Class<?> controllerClass,Class<E> resourceType) {
super(controllerClass,resourceType);
model = resourceType;
}
@Override
protected E instantiateModel(T entity) {
try {
Constructor<E> constructor = model.getConstructor(entity.getClass());
return constructor.newInstance(entity);
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException("lỗi server");
}
}
@Override
public E toModel(T entity) {
Class<?> clazz = entity.getClass();
try {
Method method = clazz.getMethod("getId");
Object id = method.invoke(entity);
return createModelWithId(id,entity);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException("lỗi server");
}
}
}
它可以工作,但我必须使用 java 反射,这可能会导致性能问题,因为 toModel
被每个请求调用。
是否有其他方法可以概括 RepresentationModelAssemblerSupport
?
以下是 Model 类的示例:
@Relation(collectionRelation = "products",itemRelation = "product")
@Getter
public class ProductModel extends RepresentationModel<ProductModel> {
private final UUID id;
private final String name;
private final Integer price;
private final String description;
public ProductModel(Product product) {
this.id = product.getId();
this.name = product.getName();
this.price = product.getPrice();
this.description = product.getDescription();
add(linkTo(methodOn(ProductController.class).getProductColors(product.getId())).withRel("productColors"));
add(linkTo(methodOn(ProductController.class).getProductTags(product.getId())).withRel("productTags"));
add(linkTo(methodOn(ThumbnailController.class).getThumbnail(product.getThumbnail().getId())).withRel("thumbnail"));
add(linkTo(methodOn(ProductController.class).all(0,new PagedResourcesAssembler<>(null,null))).withRel("all"));
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。