Spring Data Rest: RepositoryEventHandler methods not invoked

核能气质少年 提交于 2019-11-27 05:40:44

问题


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
}

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());

    }
}

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();
    }
}

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

I'm using: Spring Boot 1.1.5.RELEASE


回答1:


Sometimes obvious mistakes go unnoticed.

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.




回答2:


How does your main Application class look like? Does it import the RepositoryRestMvcConfiguration as described in https://spring.io/guides/gs/accessing-data-rest/?



来源:https://stackoverflow.com/questions/25510530/spring-data-rest-repositoryeventhandler-methods-not-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!