如何以编程方式注册AbstractMongoEventListener?

3
在我的Spring Boot应用程序中,我有一个配置,它从Mongo数据库中读取条目。完成这个操作后,我的AbstractMongoEventListener子类被创建,尽管它在不同的表和范围(我的自定义@CustomerScope)上运行。以下是监听器代码:
@CustomerScoped
@Component
public class ProjectsRepositoryListener extends AbstractMongoEventListener<Project> {

    @Override
    public void onAfterSave(Project source, DBObject dbo) {
        System.out.println("saved");
    }
}

以下是配置信息:

@Configuration
public class MyConfig {

    @Autowired
    private CustomersRepository customers;

    @PostConstruct
    public void initializeCustomers() {
        for (Customer customer : customers.findAll()) {
            System.out.println(customer.getName());
        }
    }
}

我觉得听者被实例化有些令人惊讶,特别是因为它在顾客仓库的调用结束后才被实例化。是否有一种方法可以防止这种情况发生?我正在考虑在每个表/范围内通过编程方式进行注册,而不使用注释魔法。
1个回答

3
为了避免自动实例化,监听器不能被注释为@Component。配置需要获取ApplicationContext,可以进行自动装配。

因此,我的配置类如下所示:
@Autowired
private AbstractApplicationContext context;

private void registerListeners() {
    ProjectsRepositoryListener firstListener = beanFactory.createBean(ProjectsRepositoryListener.class);
    context.addApplicationListener(firstListener);

    MySecondListener secondListener = beanFactory.createBean(MySecondListener.class);
    context.addApplicationListener(secondListener);
}

请注意,这适用于任何 ApplicationListener,而不仅仅是 AbstractMongoEventListener

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接