简体   繁体   中英

How to use a Spring bean as a Morphia entity listener?

The Morphia documentation provides an example on how @EntityListeners can be used to externalize life cycle methods to a separate class:

@EntityListeners(DigitalSigner.class)
public class BankAccount {
  @Id
  String id;
  Date lastUpdated = new Date();
}

class DigitalSigner {
  @PrePersist
  void prePersist(final Object entity, final DBObject dbObject) {
     dbObject.put("signature", sign(dbObject));
  }
}

However, the documentation doesn't state how the class is instantiated. My guess is by calling the no-args constructor.

I need to call a Spring service from the entity listener or have the Spring service work as the listener. How can this be achieved (preferably without sticking the service into a static field)?

The functionality is provided by the ObjectFactory class, which can be set using MapperOptions.setObjectFactory . The custom ObjectFactory should return the appropriate Spring beans for the requested class types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM