Spring框架:ContextRefreshedEvent被多次触发

时间:2019-04-16 18:18:05

标签: spring spring-boot

在某些情况下,例如在Spring应用@EnableBinding上启用绑定,ContextRefreshedEvent开始被触发多次。

例如,

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");
        }
    }

如果您删除@EnableBinding批注,ContextRefreshedEvent将仅被触发一次。

如果添加它,则该事件将被触发5次。

1 个答案:

答案 0 :(得分:0)

您需要像这样检查特定的ApplicationContext:

@Autowired
ApplicationContext applicationContext;

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