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 😉 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 AbstractEntityListener :

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 AutowireHelper . That’s the core of the dependency injection in the Hibernate entity listeners:

This AutowireHelper  implements the ApplicationContextAware  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 is not needed but it’s a small performance optimization)

You just need to register this AutowireHelper in your XML or Java Spring configuration and you have fully working Spring dependency injection in Hibernate entity listeners.

Have a nice weekend,

Cheers

Guy

 125,056 total views,  12 views today

Share Post :

33 Comments

  • Sidi
    May 9, 2020 10:51 PM at 10:51 PM  - Reply

    what a help, greatful. thanks

Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.