Thursday, July 1, 2010

Execute cleaning callback after Spring shuts down

I develop some fancy database management framework for purpose of integration testing. This includes calling PosgtreSQL client process from Java using the exec.

Such approach leads to the problem with cleaning the database (dropdb) after the tests. That happens because my testing beans are disposed before the Hibernate's SessionFactory (and you cannot delete database with connections opened by sessionFactory).

I could use the depends-on="dbTestFixtureBean" on sessionFactory bean definition. That would initialize my testing tool before the sessionFactory and therefore dispose my tool bean after the sessionFactory is destroyed. However my sessionFactory XML definition has to be unaware of the testing tools.

My solution? Runtime#addShutdownHook(). Since I use Groovy I use:

@Override
void afterPropertiesSet() {
  createDBFixture()
  addShutdownHook {cleanDBFixture()}
}

My cleaning callback is then called after the current thread is disposed.

No comments:

Post a Comment