javaspring-boot

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?


Solution

  • 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);