我如何以编程方式注册 AbstractMongoEventListener? [英] How do i register AbstractMongoEventListener programmatically?
问题描述
在我的 Spring Boot 应用程序中,我有一个配置,它从 Mongo 数据库读取条目.
完成后,创建了我的 AbstractMongoEventListener
子类,即使它在不同的表和不同的范围(我自己的自定义 @CustomerScope
)上运行.>
这里是听众:
@CustomerScoped@成分公共类 ProjectsRepositoryListener 扩展 AbstractMongoEventListener<Project>{@覆盖public void onAfterSave(项目源,DBObject dbo){System.out.println("保存");}}
这里是配置:
@Configuration公共类 MyConfig {@自动连线私人客户存储库客户;@PostConstruct公共无效初始化客户(){对于(客户客户:customers.findAll()){System.out.println(customer.getName());}}}
我发现完全实例化侦听器令人惊讶.特别是因为它在对客户存储库的调用完成后被很好地实例化.
有没有办法防止这种情况发生?我正在考虑以编程方式为每个表/范围注册它,没有注释魔法.
为了防止自动实例化,监听器不能被注解为 @Component
.配置需要获取可以自动装配的 ApplicationContext.
因此,我的配置类如下所示:
@Autowired私有 AbstractApplicationContext 上下文;私有无效 registerListeners() {ProjectsRepositoryListener firstListener = beanFactory.createBean(ProjectsRepositoryListener.class);context.addApplicationListener(firstListener);MySecondListener secondListener = beanFactory.createBean(MySecondListener.class);context.addApplicationListener(secondListener);}
请注意,这适用于任何 ApplicationListener
,而不仅仅是 AbstractMongoEventListener
.
In my Spring Boot application, i have a configuration, which reads entries from a Mongo database.
After this is done, my subclass of AbstractMongoEventListener
is created, even though it operates on a different table and different scope (my own custom @CustomerScope
).
Here is the listener:
@CustomerScoped
@Component
public class ProjectsRepositoryListener extends AbstractMongoEventListener<Project> {
@Override
public void onAfterSave(Project source, DBObject dbo) {
System.out.println("saved");
}
}
And here the configuration:
@Configuration
public class MyConfig {
@Autowired
private CustomersRepository customers;
@PostConstruct
public void initializeCustomers() {
for (Customer customer : customers.findAll()) {
System.out.println(customer.getName());
}
}
}
I find it surprising that the listener is instantiated at all. Especially since it is instantiated well after the call to the customers repository has finished.
Is there a way to prevent this? I was thinking of programmatically registering it per table/scope, without annotation magic.
To prevent auto-instantiation, the listener must not be annotated as @Component
. The configuration needs to get ahold of the ApplicationContext, which can be autowired.
Thus, my configuration class looks like this:
@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);
}
Note that this works for any ApplicationListener
, not just AbstractMongoEventListener
.
这篇关于我如何以编程方式注册 AbstractMongoEventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!