Skip to content

Commit 6c3a719

Browse files
committed
Add classpath check for context-propagation
See gh-29056
1 parent dedcb19 commit 6c3a719

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
import org.springframework.http.server.ServerHttpResponse;
4848
import org.springframework.lang.Nullable;
4949
import org.springframework.util.Assert;
50+
import org.springframework.util.ClassUtils;
5051
import org.springframework.util.CollectionUtils;
5152
import org.springframework.util.MimeType;
5253
import org.springframework.web.HttpMediaTypeNotAcceptableException;
@@ -81,6 +82,9 @@ class ReactiveTypeHandler {
8182
private static final List<MediaType> JSON_STREAMING_MEDIA_TYPES =
8283
Arrays.asList(MediaType.APPLICATION_NDJSON, MediaType.APPLICATION_STREAM_JSON);
8384

85+
private static final boolean isContextPropagationPresent = ClassUtils.isPresent(
86+
"io.micrometer.context.ContextSnapshot", ReactiveTypeHandler.class.getClassLoader());
87+
8488
private static final Log logger = LogFactory.getLog(ReactiveTypeHandler.class);
8589

8690

@@ -133,13 +137,8 @@ public ResponseBodyEmitter handleValue(Object returnValue, MethodParameter retur
133137
ReactiveAdapter adapter = this.adapterRegistry.getAdapter(clazz);
134138
Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz);
135139

136-
if (Mono.class.isAssignableFrom(clazz)) {
137-
ContextSnapshot snapshot = ContextSnapshot.captureAll();
138-
returnValue = ((Mono<?>) returnValue).contextWrite(snapshot::updateContext);
139-
}
140-
else if (Flux.class.isAssignableFrom(clazz)) {
141-
ContextSnapshot snapshot = ContextSnapshot.captureAll();
142-
returnValue = ((Flux<?>) returnValue).contextWrite(snapshot::updateContext);
140+
if (isContextPropagationPresent) {
141+
returnValue = ContextSnapshotHelper.writeReactorContext(returnValue);
143142
}
144143

145144
ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
@@ -512,4 +511,22 @@ public ResolvableType getReturnType() {
512511
}
513512
}
514513

514+
515+
private static class ContextSnapshotHelper {
516+
517+
public static Object writeReactorContext(Object returnValue) {
518+
if (Mono.class.isAssignableFrom(returnValue.getClass())) {
519+
ContextSnapshot snapshot = ContextSnapshot.captureAll();
520+
return ((Mono<?>) returnValue).contextWrite(snapshot::updateContext);
521+
}
522+
else if (Flux.class.isAssignableFrom(returnValue.getClass())) {
523+
ContextSnapshot snapshot = ContextSnapshot.captureAll();
524+
return ((Flux<?>) returnValue).contextWrite(snapshot::updateContext);
525+
}
526+
else {
527+
return returnValue;
528+
}
529+
}
530+
}
531+
515532
}

0 commit comments

Comments
 (0)