问题
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