|
47 | 47 | import org.springframework.http.server.ServerHttpResponse;
|
48 | 48 | import org.springframework.lang.Nullable;
|
49 | 49 | import org.springframework.util.Assert;
|
| 50 | +import org.springframework.util.ClassUtils; |
50 | 51 | import org.springframework.util.CollectionUtils;
|
51 | 52 | import org.springframework.util.MimeType;
|
52 | 53 | import org.springframework.web.HttpMediaTypeNotAcceptableException;
|
@@ -81,6 +82,9 @@ class ReactiveTypeHandler {
|
81 | 82 | private static final List<MediaType> JSON_STREAMING_MEDIA_TYPES =
|
82 | 83 | Arrays.asList(MediaType.APPLICATION_NDJSON, MediaType.APPLICATION_STREAM_JSON);
|
83 | 84 |
|
| 85 | + private static final boolean isContextPropagationPresent = ClassUtils.isPresent( |
| 86 | + "io.micrometer.context.ContextSnapshot", ReactiveTypeHandler.class.getClassLoader()); |
| 87 | + |
84 | 88 | private static final Log logger = LogFactory.getLog(ReactiveTypeHandler.class);
|
85 | 89 |
|
86 | 90 |
|
@@ -133,13 +137,8 @@ public ResponseBodyEmitter handleValue(Object returnValue, MethodParameter retur
|
133 | 137 | ReactiveAdapter adapter = this.adapterRegistry.getAdapter(clazz);
|
134 | 138 | Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz);
|
135 | 139 |
|
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); |
143 | 142 | }
|
144 | 143 |
|
145 | 144 | ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
|
@@ -512,4 +511,22 @@ public ResolvableType getReturnType() {
|
512 | 511 | }
|
513 | 512 | }
|
514 | 513 |
|
| 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 | + |
515 | 532 | }
|
0 commit comments