In JPA I want to utilize the PrePersist
annotated method to perform some operations but rather than making the things it needs to implement the Singleton pattern (with getInstance() etc.) I was wondering if I pass the Spring ApplicationContext through a ThreadLocal (which I close release after the request) would be a safe thing to do so. I am only using it primarilly to getBean(Support.class)
and not modifying the context.
Is it safe to pass in the Spring Application Context into a ThreadLocal associated with a request?
Asked Answered
If you can use Hibernate event listeners I wrote once a response with a possible approach for Spring managed event listeners here:
Using Hibernate 4's Integrator pattern and Spring's dependency injection
Thanks, though I gave a context of JPA, my question is whether there may be any ill effects of using ThreadLocal to pass the ApplicationContext. –
Flaviaflavian
You dont need to pass the ApplicationContext in a threadlocal. You can just create a class with a static member (autowired with the setter) to retrieve the context. You need to be aware that the context can be missing on startup though! –
Lita
Other than that you need to be aware that you can not do anything you like in those listeners. Creating other entities for example might fail as the whole hibernate process will not take place recursively and another prepersist will not be called. At least it was like that with Hibernate 4. The documentation mentions some pitfalls if I remember right. –
Lita
© 2022 - 2025 — McMap. All rights reserved.
ApplicationContext
around and to prevent fetching beans in an entity-class: is using anEntityListener
a possibility? – CliqueSupport
bean? – WavelliteSupport
bean? – FlaviaflavianSupport
bean in the prepersist-phase? – CliquegetBean(Support.class)
. Just pass that instance instead of the context. – WavelliteSupport
-bean around in theThreadLocal
. – Clique