在我的 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());
}
}
}
我对监听器被实例化感到惊讶。特别是因为它是在对客户存储库的调用完成后很好地实例化的。
有办法防止这种情况发生吗?我正在考虑以编程方式按表/范围注册它,而不使用注释魔法。
最佳答案
为了防止自动实例化,监听器不得注释为@Component
。配置需要获取可以 Autowiring 的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
。
关于java - 如何以编程方式注册 AbstractMongoEventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37297262/