未调用AbstractMongoEventListener

时间:2018-04-06 19:50:43

标签: spring spring-data spring-data-mongodb

我有以下课程

class MongoCascadeSaveEventListener extends AbstractMongoEventListener<Object> {

    @Override
    public void onBeforeConvert(final BeforeConvertEvent<Object> event) {
    }
}

Bean定义

@Bean
public MongoCascadeSaveEventListener mongoCascadeSaveEventListener() {
    return new MongoCascadeSaveEventListener();
}

onBeforeConvert永远不会被召唤。

当我检查MongoTemplate类时,事件发布者设置如下

eventPublisher = new MongoMappingEventPublisher(indexCreator);

来自spring mongo包的课程。当我看到这个类时,我不认为实现是正确的,这就解释了为什么不调用监听器。

public class MongoMappingEventPublisher implements ApplicationEventPublisher {

    private final MongoPersistentEntityIndexCreator indexCreator;

    /**
     * Creates a new {@link MongoMappingEventPublisher} for the given {@link MongoPersistentEntityIndexCreator}.
     * 
     * @param indexCreator must not be {@literal null}.
     */
    public MongoMappingEventPublisher(MongoPersistentEntityIndexCreator indexCreator) {

        Assert.notNull(indexCreator, "MongoPersistentEntityIndexCreator must not be null!");
        this.indexCreator = indexCreator;
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.context.ApplicationEventPublisher#publishEvent(org.springframework.context.ApplicationEvent)
     */
    @SuppressWarnings("unchecked")
    public void publishEvent(ApplicationEvent event) {
        if (event instanceof MappingContextEvent) {
            indexCreator.onApplicationEvent((MappingContextEvent<MongoPersistentEntity<?>, MongoPersistentProperty>) event);
        }
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.context.ApplicationEventPublisher#publishEvent(java.lang.Object)
     */
    public void publishEvent(Object event) {}
}

这是一个错误还是我错过了什么?使用2.0.5。发布spring数据mongo。

1 个答案:

答案 0 :(得分:0)

你的配置看起来很好,应该调用监听器,MongoTemplate实现ApplicationContextAware,因此在构造之后它将eventPublisher设置为applicationContext