3

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");
                }
            }
        };
    }

}
sparkyspider
  • 13,195
  • 10
  • 89
  • 133

1 Answers1

2

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);
Luanne
  • 19,145
  • 1
  • 39
  • 51
  • it works fine, but if I created a repository interface and call the save method on the repository, then the event would not be fire, as I would expect. – nils Jul 06 '15 at 13:41
  • A Jira issue has been filed for this: https://jira.spring.io/browse/DATAGRAPH-710. – tstorms Sep 22 '15 at 12:44
  • 1
    It's been a long time about this issue...any news about the change of firing events saving through repositories? Or use the template is the way to proceed? Thanks – troig Jul 21 '16 at 16:46