Spring Data Rest ResourceProcessor未应用于预测

时间:2017-11-01 04:11:05

标签: spring-data-rest

我正在使用ResourceProcessor在集合中列出或单独提取时向我的资源对象添加其他链接。但是,当我将投影(或摘录项目)应用于我的存储库时,ResourceProcessor不会运行,因此我的链接不会被创建。是否有办法允许将自定义资源链接添加到资源,而不管资源内容的投影方式如何?

1 个答案:

答案 0 :(得分:1)

我认为这个问题描述了你的情况: http://localhost:8983/solr/your_core_name/

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

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

我们有一个基类,能够获取投影的基础实体,并调用实体ResourceProcessor并将链接应用于投影。 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);
    }
}

实现本身只传递可以处理实体类的ResourceProcessor并将其传递给我们的ProjectionResourceProcessor。它不包含任何链接创建逻辑。