Как создать пользовательский PersistentEntityResourceAssembler с помощью Spring Data REST - PullRequest
0 голосов
/ 06 июня 2019

Я использую Spring Boot 2.1, Spring Data REST, Spring HATEOAS, Hibernate 5.

Я ищу способ фильтрации полей в вызовах REST.Я собираюсь использовать https://github.com/bohnman/squiggly-java, но я хочу интегрировать его в ассемблер ресурсов Spring.

Я ищу способ настроить PersistentEntityResourceAssembler, который автоматически доступен в контроллерах REST.Это код класса:

public class PersistentEntityResourceAssembler implements ResourceAssembler<Object, PersistentEntityResource> {
    @NonNull
    private final PersistentEntities entities;
    @NonNull
    private final Projector projector;
    @NonNull
    private final Associations associations;
    @NonNull
    private final SelfLinkProvider linkProvider;
    @NonNull
    private final EmbeddedWrappers wrappers = new EmbeddedWrappers(false);

    public PersistentEntityResource toResource(Object instance) {
        Assert.notNull(instance, "Entity instance must not be null!");
        return this.wrap(this.projector.projectExcerpt(instance), instance).build();
    }

    public PersistentEntityResource toFullResource(Object instance) {
        Assert.notNull(instance, "Entity instance must not be null!");
        return this.wrap(this.projector.project(instance), instance).build();
    }

    private Builder wrap(Object instance, Object source) {
        PersistentEntity<?, ?> entity = this.entities.getRequiredPersistentEntity(source.getClass());
        return PersistentEntityResource.build(instance, entity).withEmbedded(this.getEmbeddedResources(source)).withLink(this.getSelfLinkFor(source)).withLink(this.linkProvider.createSelfLinkFor(source));
    }

    private Iterable<EmbeddedWrapper> getEmbeddedResources(Object instance) {
        return (new EmbeddedResourcesAssembler(this.entities, this.associations, this.projector)).getEmbeddedResources(instance);
    }

    public Link getSelfLinkFor(Object instance) {
        Link link = this.linkProvider.createSelfLinkFor(instance);
        return new Link(link.expand(new Object[0]).getHref(), "self");
    }

    public PersistentEntityResourceAssembler(@NonNull PersistentEntities entities, @NonNull Projector projector, @NonNull Associations associations, @NonNull SelfLinkProvider linkProvider) {
        if (entities == null) {
            throw new IllegalArgumentException("entities is marked @NonNull but is null");
        } else if (projector == null) {
            throw new IllegalArgumentException("projector is marked @NonNull but is null");
        } else if (associations == null) {
            throw new IllegalArgumentException("associations is marked @NonNull but is null");
        } else if (linkProvider == null) {
            throw new IllegalArgumentException("linkProvider is marked @NonNull but is null");
        } else {
            this.entities = entities;
            this.projector = projector;
            this.associations = associations;
            this.linkProvider = linkProvider;
        }
    }
}

Я предполагаю, что он вводится где-то в Spring.Я хочу настроить содержимое JSON, динамически отфильтровывая ненужные мне поля.Я пытался создать копию класса и аннотировать ее с помощью @Component, но в ней отсутствует Projector.

Как правильно настроить PersistentEntityResourceAssembler в Spring Data REST?

1 Ответ

1 голос
/ 06 июня 2019

Вы должны создать PersistentEntityResourceAssemblerArgumentResolver, который создает PersistentEntityResourceAssembler на лету, если он нужен методу контроллера.

Это работает так, потому что PersistentEntityResourceAssembler требует projectionпараметр из запроса, поэтому он не может быть bean.

Сам преобразователь аргументов зарегистрирован в классе RepositoryRestMvcConfiguration.Это определено в его защищенном методе: defaultMethodArgumentResolvers().К сожалению, его нельзя настроить с помощью RepositoryRestConfigurer, поэтому вам нужно расширить сам класс конфигурации RepositoryRestMvcConfiguration, а затем переопределить метод defaultMethodArgumentResolvers().

К сожалению, этот метод также создает множество других argumentsResolvers, поэтому я думаю,Наилучший подход - если вы вызываете метод super, удаляете исходный PersistentEntityResourceAssemblerArgumentResolver из возвращаемого списка и добавляете в него свой собственный.

Это не будет такой простой задачей ... удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...