Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i register AbstractMongoEventListener programmatically?

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.

like image 656
Johannes Dorn Avatar asked May 08 '26 16:05

Johannes Dorn


1 Answers

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.

like image 55
Johannes Dorn Avatar answered May 11 '26 06:05

Johannes Dorn