guy labs guy labs

Autowiring Spring beans in Hibernate/JPA entity listeners

After a long time without a post I will write something about Spring dependency injection in Hibernate/JPA entity listeners. The problem here is that you are not able to just autowire a Spring bean in a Hibernate/JPA entity listener, because Hibernate for instance instantiates the entity listener before Spring can autowire the beans and therefore all the autowired beans are null. I found some some other ways to autowire the beans which specify which listeners should be registered in a Hibernate configuration class, but the way I will show you in this post is the simplest one in my opinion. Other opinions are also welcome :wink: I found the idea here at Stackoverflow. In the following example I want to show you how to add a JPA listener which always sets a creation date and a modification date when a entity is created/modified. Ok lets start by a simple abstract JPA entity: Here there is nothing special except the : And here you already see that we have an autowired Spring bean which returns the current date. This entity listener listens for the pre-update and the pre-persist events and sets the according dates. There is also the static call to the autowire method of the . That's the core of the dependency injection in the Hibernate entity listeners: This  implements the  interface from Spring with which the helper is able to get a reference of the application context. The autowire method takes the class instance which needs to be autowired and the beans which need to be autowired. (This...