spring-cloud-gateway icon indicating copy to clipboard operation
spring-cloud-gateway copied to clipboard

Skip route refresh after the context starts shutting down

Open PreAgile opened this issue 6 months ago • 0 comments

Summary

Stops CachingRouteLocator from delegating to the wrapped RouteLocator once the ApplicationContext has begun closing. The listener was firing on RefreshRoutesEvent instances published during the destroy phase (typically by ConsulServiceRegistry.deregister()), which led the delegate path to ask the BeanFactory for beans that were already being destroyed and produced the BeanCreationNotAllowedException reported in gh-2471.

Why isActive() is not enough

The first instinct is AbstractApplicationContext.isActive(), but active only flips to false at the very end of doClose() — after destroyBeans() has already run. The first signal available is ContextClosedEvent, published in step 1 of doClose(), before any destroy callback fires.

publishEvent(ContextClosedEvent)   // step 1
getLifecycleProcessor().onClose()  // step 2
destroyBeans()                     // step 3  ← failure happens here
...
this.active.set(false)             // step 6

The fix

When the event publisher is a ConfigurableApplicationContext, register a small ContextClosedEvent listener that flips a volatile boolean contextClosing flag, and short-circuit onApplicationEvent(RefreshRoutesEvent) when the flag is set.

public void onApplicationEvent(RefreshRoutesEvent event) {
    if (contextClosing) { return; }
    // existing logic
}

public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
    this.applicationEventPublisher = publisher;
    if (publisher instanceof ConfigurableApplicationContext context) {
        context.addApplicationListener(
            (ApplicationListener<ContextClosedEvent>) event -> this.contextClosing = true);
    }
}

+12 / -2 in CachingRouteLocator.java. No interfaces added. The existing CachingRouteLocatorTests keep passing because they wire a lambda publisher, so the new instanceof branch is skipped and the guard stays inactive — the original behaviour is preserved for non-context publishers.

Reproduction

CachingRouteLocatorShutdownTests makes the race deterministic by registering a DisposableBean whose destroy() publishes a RefreshRoutesEvent — the same timing the Consul registry exercises:

context.getDefaultListableBeanFactory().registerDisposableBean(
    "refreshOnShutdown",
    () -> context.publishEvent(new RefreshRoutesEvent(this)));
context.close();

Without the guard the test fails (expected: 1 but was: 2); with the guard it passes. The broader Route/Routing test set in spring-cloud-gateway-server-webflux (219 tests) stays green.

Happy to open a 4.3.x backport once this lands.

Fixes gh-2471

PreAgile avatar May 04 '26 07:05 PreAgile