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?
You cant actually use both of them in the same application.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With