【问题标题】:Spring Data Rest: RepositoryEventHandler methods not invokedSpring Data Rest:未调用 RepositoryEventHandler 方法
【发布时间】:2014-10-20 01:21:51
【问题描述】:

我正在尝试将Spring Data REST documentation 中所述的 RepositoryEventHandler 添加到如下所示的 REST 存储库:

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

我创建了一个 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 组件中声明它:

@Configuration
public class RepositoryConfiguration {

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

        return new AgentEventHandler();
    }
}

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

我正在使用:Spring Boot 1.1.5.RELEASE

【问题讨论】:

  • 如果你宁愿扩展AbstractRepositoryEventListener,它是否有效?
  • @OliverGierke(感谢您的介入)不,没有区别 [公共类 AgentEventHandler 扩展 AbstractRepositoryEventListener] 也 [公共类 AgentEventHandler 扩展 AbstractRepositoryEventListener]
  • 你确定 RepositoryConfiguration 类被 Boot 选中了吗?如果是这样,您是否有机会创建一个失败的小示例项目并在我们的JIRA 中创建票证?
  • @OliverGierke 我认为是(我在 agentEvenHandler 方法中添加了一个 System.out.println("registering AgentEventHandler");...如果有更好的方法来检查这个,请告诉我) . Jira:我试试看!
  • @OliverGierke 不确定这是否真的是一个错误或我配置错误的东西。所以我在github 上推送了一个示例项目,而不是创建票证。

标签: java spring spring-data spring-data-rest


【解决方案1】:

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

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

现在我的(清理后的)demo app 测试成功通过。

【讨论】:

  • 在我开始自己做一个小矩阵之前,在特定的 HTTP 调用上发出哪些事件,这是否记录在某个地方?我查看了 Spring Data REST 文档,但它只提到了事件,没有详细说明它们将被发送到哪个 HTTP 调用。
  • @Beamie 我进行了快速搜索,但找不到任何将 Spring Data REST 事件与 HTTP 动词相关联的文档。以下应该可以工作:POST=>*CreateEvent、PUT=>*SaveEvent、DELETE=>*DeleteEvent。详细活动列表:docs.spring.io/spring-data/rest/docs/current/reference/html/…
  • 未来读者请注意:如果您覆盖默认控制器方法,则不会调用事件(BeforeCreate、BeforeSave 等),因此请记住这一点。
【解决方案2】:

您的主要应用程序类是什么样的?它是否按照https://spring.io/guides/gs/accessing-data-rest/ 中的描述导入 RepositoryRestMvcConfiguration?

【讨论】:

  • Marcel:我在github 上推送了一个示例项目。感谢您的帮助。
猜你喜欢
  • 2017-02-19
  • 2015-12-24
  • 2019-01-31
  • 2020-01-15
  • 1970-01-01
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多