The Persistence Infrastructure provides automatically dispatched events for all entity classes. To use these events all you need to do is write event listeners and wire them using Guice, very much as described in the previous section. The event interface for persistence events differs from the previous example in that it is a parameterized abstract class called PersistenceEvent, which takes the name of the entity as a type parameter.
See the Javadoc for the PersistenceEvent class for a complete list of methods. Default empty implementations are provided for all event methods. In the example following, a listener is written which implements just the postInsert method of PersistenceEvent for an entity called MyEntity:
package curam.mypackage; import com.google.inject.Singleton; import curam.util.persistence.PersistenceEvent; @Singleton final class MyListener implements PersistenceEvent<MyEntity> { protected MyListener() { // Protected constructor for use only by Guice } @Override public void postInsert(final MyEntity entity) throws InformationalException, AppException { // handle the event here } }
As for other events, you have to wire your listener implementation in a Guice module:
@Override public void configure() { /* * Get the listener set */ Multibinder<PersistenceEvent<MyEntity>> myEventListeners = Multibinder.newSetBinder(binder(), new TypeLiteral<PersistenceEvent<MyEntity>>() { /**/ }); /* * Add a listener */ myEventListeners.addBinding().to(MyListener.class); }