Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ignore an ApplicationListener defined in spring.factories?

I'm importing a Spring Boot Starter in my project because it contains a class I would like to use but I don't want auto configuration to run. I can see in the starter that there is a META-INF/spring.factories file which has both auto configurations as well as application listeners defined.

# Auto Configurations
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    org.demo.SomeAutoConfiguration,\
    org.demo.AnotherAutoConfiguration

# Application Listeners
org.springframework.context.ApplicationListener=\
    org.demo.SomeApplicationListener,\
    org.demo.AnotherApplicationListener

I've figured out how to exclude specific classes from auto configuration and this works great.

@SpringBootApplication(exclude={SomeAutoConfiguration.class, AnotherAutoConfiguration.class})

Now I can't seem to figure out how to exclude one or more of these application listeners. Any ideas?

like image 536
Blaine Avatar asked Sep 14 '25 07:09

Blaine


2 Answers

There's no built-in support for ignoring certain application listeners. However, you could subclass SpringApplication, override SpringApplication.setListeners(Collection<? extends ApplicationListener<?>>) and filter out the listeners that you don't want:

    new SpringApplication(ExampleApplication.class) {

        @Override
        public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
            super.setListeners(listeners
                    .stream()
                    .filter((listener) -> !(listener instanceof UnwantedListener))
                    .collect(Collectors.toList()));
        }

    }.run(args);
like image 146
Andy Wilkinson Avatar answered Sep 15 '25 21:09

Andy Wilkinson


I suggest to use SpringApplicationRunListener:

class AppListenerExcluder implements SpringApplicationRunListener {

    AppListenerExcluder(SpringApplication app, String[] args) {
        app.setListeners(
                app.getListeners().stream()
                        .filter(not(listener -> listener instanceof UnwantedListener))
                        .toList());
    }
}

We have to declare It in spring.factories in app "resources" folder:
src
ㅤmain
ㅤㅤresources
ㅤㅤㅤMETA-INF
ㅤㅤㅤㅤspring.factories

ㅤㅤㅤㅤㅤorg.springframework.boot.SpringApplicationRunListener=\
ㅤㅤㅤㅤ  ㅤdev.rost.client.config.AppListenerExcluder

GitHub 🔗

like image 30
Rostik Avatar answered Sep 15 '25 22:09

Rostik