yeralin
yeralin

Reputation: 1407

Spring Framework: ContextRefreshedEvent is fired multiple times

Under certain cases like enabling binding on Spring app @EnableBinding,ContextRefreshedEvent starts getting fired multiple times.

For example,

public interface MessageBinding {
    @Input("test")
    KStream<Long, String> messagesIn();
}

@EnableBinding(MessageBinding.class)
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Component
    public static class ComponentX {

        @Autowired
        ApplicationContext applicationContext;

        @EventListener
        public void onApplicationEvent(ContextRefreshedEvent event) {
            System.out.println("Fired event");
        }
    }

If you remove @EnableBinding annotation, ContextRefreshedEvent will only be fired once.

If you add it, the event will be fired 5 times.

Upvotes: 5

Views: 2039

Answers (1)

yeralin
yeralin

Reputation: 1407

You would need to check for your specific ApplicationContext like this:

@Autowired
ApplicationContext applicationContext;

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
    if (event.getApplicationContext().equals(this.applicationContext)) {
        System.out.println("Fired only once!");
    }
}

Upvotes: 9

Related Questions