我使用 Spring Boot,运行 v1.5.1.RELEASE、Spring v4.3.6.RELEASE。我试图对 JPA 事件监听器进行一些巧妙的处理,但它不起作用;
我的实体看起来像这样
@Entity
@EntityListeners({MyEntityListener.class})
public class Entity extends SomeOtherEntity implements SomeInterfaceForAudit {
}
我的 EventListener 类如下所示
public class MyEntityListener extends EntityListener<SchoolAdmin> {
// some other useful things in here...
}
我的“聪明”在于我尝试像这样“泛化”EntityListener;
公共(public)抽象类EntityListener {
public abstract class EntityListener<T> {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@PostUpdate
@PostConstruct
@PostRemove
public void queueForIndex(T entity) {
logger.info("queueForIndex " + entity.toString());
}
}
}
没有完成任何日志记录。我尝试在我的实体类中创建这样的方法
@PostUpdate
public void reIndex() {
System.out.println("--- post update-- ---- -<<<--- " + entity);
}
这有效。我不明白为什么我的通用版本不应该工作?有人吗?
最佳答案
如果你查看官方文档,对于jpa实体生命周期回调注释,你会发现那里没有@Inherited
注释。此元注释导致注释从父类(super class)继承。由于它不在这些回调方法注释中,子类将不知道它们在父类(super class)中的存在。正是在您的情况下,MyEntityListener.class 通过继承获取queueForIndex(T实体)方法作为普通方法,而不是作为实体生命周期回调方法。
仅显示一个作为示例引用: http://docs.oracle.com/javaee/6/api/javax/persistence/PostUpdate.html
@Target(value=METHOD)
@Retention(value=RUNTIME)
public @interface PostUpdate
关于java - JPA 事件监听器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285023/