How do i register AbstractMongoEventListener programmatically?

北慕城南 提交于 2021-02-07 10:50:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37297262/how-do-i-register-abstractmongoeventlistener-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!