@RepositoryEventHandler events stop with @RepositoryRestController

前端 未结 1 1226
野性不改
野性不改 2021-01-13 17:43

When I create a @RepositoryRestController for an entity, the associated @RepositoryEventHandler methods are not triggered in Spring Data REST via S

相关标签:
1条回答
  • 2021-01-13 18:14

    It's as implemented. :-)

    The methods defined in a @RepositoryRestController implementation replace the methods in the default RepositoryEntityController which publish @RepositoryEventHandler events.

    But it's easy to add these events making the @RepositoryRestControll a ApplicationEventPublisherAware implementation and publishing the events like the default RepositoryEntityController implementation:

    @Slf4j
    @RepositoryRestController
    @AllArgConstructor
    public class AccountRespositoryRestController 
        implements ApplicationEventPublisherAware {
    
        private final AccountRepository repository;
        private ApplicationEventPublisher publisher;
    
        @Override
        public void setApplicationEventPublisher(
            ApplicationEventPublisher publisher) {
            this.publisher = publisher;
        }
    
        @RequestMapping(method = RequestMethod.POST,value = "/accounts")
        public @ResponseBody PersistentEntityResource post(
            @RequestBody Account account,
            PersistentEntityResourceAssembler assembler) {
    
            // ...
            publisher.publishEvent(new BeforeCreateEvent(account));
            Account entity = this.repository.save(account);
            publisher.publishEvent(new AfterCreateEvent(entity));
    
            return assembler.toResource(entity);
        }
    }
    

    You can also inject the publisher without making the class ApplicationEventPublisherAware:

    @Slf4j
    @RepositoryRestController
    @AllArgConstructor
    public class AccountRespositoryRestController {
    
        private final AccountRepository repository;
        private final ApplicationEventPublisher publisher;
    
        @RequestMapping(method = RequestMethod.POST,value = "/accounts")
        public @ResponseBody PersistentEntityResource post(
            @RequestBody Account account,
            PersistentEntityResourceAssembler assembler) {
    
            // ...
            publisher.publishEvent(new BeforeCreateEvent(account));
            Account entity = this.repository.save(account);
            publisher.publishEvent(new AfterCreateEvent(entity));
    
            return assembler.toResource(entity);
        }
    }
    
    0 讨论(0)
提交回复
热议问题