Oct 11th, 2010, 07:16 AM
Putting context information on the spring context
I want to lazily invoke some action exactly once per transaction and database. To accomplish this, I used a ThreadLocal map remembering what I already put in. But in environments that use thread pools (Tomcat), on reused threads the map already contains the value from an older transaction.
After some investigation, I see two solutions for this:
1) clear my ThreadLocal map when an transaction finishes
TransactionSynchronization#afterCompletion(int) seems to be the right callback hook, but I can't see how to register this hook.
2) Instead of using my own ThreadLocal helper classes, use Springs TX transaction support classes to bind some information to the TX
TransactionSynchronizationManager#bindResource(key , resource) / getResource(key) looks like a promising starting point.
My questions: What's the preferred way to bind TX-context-information? Are there any good and simple examples available anywhere (Google didn't help me)?
Thanks in advance!