在某些情况下,例如在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次。
答案 0 :(得分:0)
您需要像这样检查特定的ApplicationContext:
@Autowired
ApplicationContext applicationContext;
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().equals(this.applicationContext)) {
System.out.println("Fired only once!");
}
}