Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting a Spring dependency into a JPA EntityListener

I am trying to inject a Spring dependency into an JPA EntityListener. Here is my listener class:

@Configurable(autowire = Autowire.BY_TYPE, dependencyCheck = true) public class PliListener {      @Autowired     private EvenementPliRepository evenementPliRepository;      @PostPersist     void onPostPersist(Pli pli) {         EvenementPli ev = new EvenementPli();         ev.setPli(pli);         ev.setDateCreation(new Date());         ev.setType(TypeEvenement.creation);         ev.setMessage("Création d'un pli");         System.out.println("evenementPliRepository: " + evenementPliRepository);         evenementPliRepository.save(ev);     }   } 

Here is my Entity class:

@RooJavaBean @RooToString @RooJpaActiveRecord @EntityListeners(PliListener.class) public class Pli implements Serializable{ ... 

However, my dependency (i.e. evenementPliRepository) is always null.

Can anyone please help?

like image 457
balteo Avatar asked Aug 28 '12 08:08

balteo


People also ask

Can we use Spring data JPA and Hibernate together?

You cant actually use both of them in the same application.


1 Answers

A hack to inject dependencies on stateless beans, is to define the dependency as "static", create a setter method so that Spring can inject the dependency (assigning it to the static dependency).

Declare the dependency as static.

static private EvenementPliRepository evenementPliRepository; 

Create a method so that Spring can inject it.

@Autowired public void init(EvenementPliRepository evenementPliRepository)  {     MyListenerClass.evenementPliRepository = evenementPliRepository;     logger.info("Initializing with dependency ["+ evenementPliRepository +"]");  } 

More details at: http://blog-en.lineofsightnet.com/2012/08/dependency-injection-on-stateless-beans.html

like image 101
Juan Jimenez Avatar answered Sep 20 '22 12:09

Juan Jimenez