Spring 数据 Rest ResourceProcessor 未应用于投影

Spring Data Rest ResourceProcessor not applied on Projections

当列在集合中或单独获取时,我正在使用 ResourceProcessor 添加额外的链接到我的资源对象。但是,当我将投影(或摘录项目)应用到我的存储库时,ResourceProcessor 没有得到 运行,因此我没有创建该资源的链接。有没有办法允许我的自定义资源链接添加到资源,而不管资源内容是如何投影的?

我认为这个问题描述的是你的情况: https://jira.spring.io/browse/DATAREST-713

目前,spring-data-rest 不提供解决您问题的功能。

我们正在使用一个小的解决方法,每个投影仍然需要一个单独的 ResourceProcessor,但我们不需要复制 link 逻辑:

我们有一个基础 class,它能够获取投影的基础实体并调用实体的 ResourceProcessor 并将 link 应用于投影。 Entity 是我们所有 JPA 实体的通用接口 - 但我认为您也可以使用 org.springframework.data.domain.Persistableorg.springframework.hateoas.Identifiable.

/**
 * Projections need their own resource processors in spring-data-rest.
 * To avoid code duplication the ProjectionResourceProcessor delegates the link creation to
 * the resource processor of the underlying entity.
 * @param <E> entity type the projection is associated with
 * @param <T> the resource type that this ResourceProcessor is for
 */
public class ProjectionResourceProcessor<E extends Entity, T> implements ResourceProcessor<Resource<T>> {

    private final ResourceProcessor<Resource<E>> entityResourceProcessor;

    public ProjectionResourceProcessor(ResourceProcessor<Resource<E>> entityResourceProcessor) {
        this.entityResourceProcessor = entityResourceProcessor;

    }

    @SuppressWarnings("unchecked")
    @Override
    public Resource<T> process(Resource<T> resource) {
        if (resource.getContent() instanceof TargetAware) {
            TargetAware targetAware = (TargetAware) resource.getContent();
            if (targetAware != null
                    && targetAware.getTarget() != null
                    && targetAware.getTarget() instanceof Entity) {
                E target = (E) targetAware.getTarget();
                resource.add(entityResourceProcessor.process(new Resource<>(target)).getLinks());
            }
        }
        return resource;
    }

}   

此类资源处理器的实现如下所示:

@Component
public class MyProjectionResourceProcessor extends ProjectionResourceProcessor<MyEntity, MyProjection> {

    @Autowired
    public MyProjectionResourceProcessor(EntityResourceProcessor resourceProcessor) {
        super(resourceProcessor);
    }
}

实现本身只是将可以处理实体 class 的 ResourceProcessor 传递给我们的 ProjectionResourceProcessor。它不包含任何 link 创建逻辑。