@RepositoryEventHandler events stop with @RepositoryRestController

柔情痞子 提交于 2019-12-01 09:56:21

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