是否有任何替代方法可以重用 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 (将#修改为@)