Spring Data Rest:未调用 RepositoryEventHandler 方法

2022-01-18 00:00:00 spring java spring-data spring-data-rest

我正在尝试按照 Spring Data REST 文档 到如下所示的 REST 存储库:

I am trying to add a RepositoryEventHandler as described on Spring Data REST documentation to the REST repository shown below:

@RepositoryRestResource(collectionResourceRel = "agents", path = "/agents")
public interface AgentRepository extends CrudRepository<Agent, Long> {
    // no implementation required; Spring Data will create a concrete Repository
}

我创建了一个 AgentEventHandler:

I created an AgentEventHandler:

@Component
@RepositoryEventHandler(Agent.class)
public class AgentEventHandler {

    /**
     * Called before {@link Agent} is persisted 
     * 
     * @param agent
     */
    @HandleBeforeSave
    public void handleBeforeSave(Agent agent) {

        System.out.println("Saving Agent " + agent.toString());

    }
}

并在@Configuration 组件中声明它:

and declared it in a @Configuration component:

@Configuration
public class RepositoryConfiguration {

    /**
     * Declare an instance of the {@link AgentEventHandler}
     *
     * @return
     */
    @Bean
    AgentEventHandler agentEvenHandler() {

        return new AgentEventHandler();
    }
}

当我发布到 REST 资源时,实体被持久化,但方法 handleBeforeSave 永远不会被调用.我错过了什么?

When I am POSTing to the REST resource, the Entity gets persisted but the method handleBeforeSave never gets invoked. What am I missing?

我正在使用:Spring Boot 1.1.5.RELEASE

I'm using: Spring Boot 1.1.5.RELEASE

推荐答案

有时明显的错误会被忽视.

Sometimes obvious mistakes go unnoticed.

POST - 使用 Spring Data REST 资源,发出 BeforeCreateEvent.要捕获此事件,必须使用 @HandleBeforeCreate 而不是 @HandleBeforeSave (后者在 PUT 和 PATCH HTTP 调用上调用)注释方法 handleBeforeSave.

POST-ing a Spring Data REST resource, emits a BeforeCreateEvent. To catch this event, the method handleBeforeSave must be annotated with @HandleBeforeCreate instead of @HandleBeforeSave (the latter gets invoked on PUT and PATCH HTTP calls).

测试在我的(清理后的)演示应用程序 现在.

Tests pass successfully on my (cleaned up) demo app now.

相关文章