问题
I'm trying to capture the BeforeSaveEvent when setting up Neo4J in Spring, so that I can call a method beforeSave()
on the class that is being saved. Unfortunately, it seems like its not being registered as a listener as non of my print statements are being executed.
Ideas appreciated.
@Configuration
@EnableNeo4jRepositories(basePackages = "com.noxgroup.nitro")
@EnableTransactionManagement
public class NitroNeo4jConfiguration extends Neo4jConfiguration {
@Bean
public Neo4jServer neo4jServer () {
System.setProperty("username", "neo4j");
System.setProperty("password", "*************");
return new RemoteServer("http://localhost:7474");
}
@Bean
public SessionFactory getSessionFactory() {
return new SessionFactory("com.noxgroup.nitro.domain");
}
@Bean
ApplicationListener<BeforeSaveEvent> beforeSaveEventApplicationListener() {
return new ApplicationListener<BeforeSaveEvent>() {
@Override
public void onApplicationEvent(BeforeSaveEvent event) {
System.out.println("Listening to event");
Object entity = event.getEntity();
if (entity instanceof NitroNode) {
((NitroNode)entity).beforeSave();
} else {
System.out.println("Not picking it up");
}
}
};
}
}
回答1:
These events are fired by Neo4jTemplate (see http://docs.spring.io/spring-data/neo4j/docs/4.0.0.M1/reference/html/#_data_manipulation_events_formerly_lifecycle_events), so that's what you'll have to use to trigger the save.
In your configuration NitroNeo4jConfiguration
include
@Bean
public Neo4jOperations getNeo4jTemplate() throws Exception {
return new Neo4jTemplate(getSession());
}
and in your application,
@Autowired
private Neo4jOperations neo4jTemplate;
which is then used to save
neo4jTemplate.save(person);
来源:https://stackoverflow.com/questions/30604863/spring-data-neo4j-4-0-0-beforesaveevent-not-firing