You can use a lazily initialized bean inside your JPAEventListener class , which is initialized when the first time entity is persisted.
Then use @Configurable on lazy loaded bean.
It may not be the best solution but a quick workaround
public class JPAEntityListener{
/**
* Hibernate JPA EntityListEner is not spring managed and gets created via reflection by hibernate library while entitymanager is loaded.
* Inorder to inject business rules via Spring use lazy loaded bean which makes use of @Configurable
*/
private CustomEntityListener listener;
public JPAEntityListener() {
super();
}
@PrePersist
public void onEntityPrePersist(TransactionalEntity entity) {
if (listener == null) {
listener = new CustomEntityListener();
}
listener.onEntityPrePersist(entity);
}
@PreUpdate
public void onEntityPreUpdate(TransactionalEntity entity) {
if (listener == null) {
listener = new CustomEntityListener();
}
listener.onEntityPreUpdate(entity);
}}
And your lazy loaded bean class
@Configurable(autowire = Autowire.BY_TYPE)
public class CustomEntityListener{
@Autowired
private Environment environment;
public void onEntityPrePersist(TransactionalEntity entity) {
//custom logic
}