SDN BeforeSaveEvent<T> capture events before save entities != T

天大地大妈咪最大 提交于 2019-12-02 09:40:59

问题


Currently I've centralized the Id creation of each NodeEntity in a BeforeSave Application Event. Something like that:

   @Inject
   IdentifierFactory identifierFactory;

   @Bean
   ApplicationListener<BeforeSaveEvent> beforeSaveEventApplicationListener() {
      return new ApplicationListener<BeforeSaveEvent>() {
         @Override
         public void onApplicationEvent(BeforeSaveEvent event) {
            if (event.getEntity() instanceof IdentifiableEntity) {
               IdentifiableEntity entity = (IdentifiableEntity) event.getEntity();
               if (entity.getId() == null) entity.setId(identifierFactory.generateId());
            }
         }
      };

This works fine.

However, In my graph model I have identifiable entities (with id attribute, implementing IdentififableEntity interface) and others non-identifiables. What I'm trying to do is capturing the before save event only if the entity is identifiable, in order to avoid the instanceof/casting:

if (event.getEntity() instanceof IdentifiableEntity)
IdentifiableEntity entity = (IdentifiableEntity) event.getEntity();

I've tried the next, but it doesn't work (the before save event continue capturing non-identifiable entities):

   @Bean
   ApplicationListener<BeforeSaveEvent<IdentifiableEntity>> beforeSaveEventApplicationListener() {
      return new ApplicationListener<BeforeSaveEvent<IdentifiableEntity>>() {
         @Override
         public void onApplicationEvent(BeforeSaveEvent<IdentifiableEntity> event) {
            if (event.getEntity() == null) event.getEntity().setId(identifierFactory.generateId());
         }
      };
   }

I'm not really sure if I can do that. I've also tried specifying a particular class (for example BeforeSaveEvent<User>) instead of an interface and I've the same problem, the event also captures other entities != User.

Can anyone clarify if what I'm trying to do is possible with spring-data-neo4j (version 3.3.0.RELEASE) and if so, an example of how can do that.

Thanks in advance.

来源:https://stackoverflow.com/questions/30106772/sdn-beforesaveeventt-capture-events-before-save-entities-t

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