Injecting a Spring dependency into a JPA EntityListener

balteo picture balteo · Aug 28, 2012 · Viewed 49.2k times · Source

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?

Answer

Juan Jimenez picture Juan Jimenez · Sep 3, 2012

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