In Spring MVC, objects like RequestAttributes
and LocaleContext
are stored in threadlocal(RequestContextHolder
, LocaleContextHolder
).
To support propagation between threadlocal and reactor operation chain, e.g. using WebClient
in MVC, I have custom ThreadLocalAccessor
(from micrometer context-propagation) implementations for them.
However, it would be more useful if Spring Framework provided them.
Sample Implementations:
public class LocaleContextThreadLocalAccessor implements ThreadLocalAccessor<LocaleContext> {
static final String KEY = "my-locale-context";
@Override
public Object key() {
return KEY;
}
@Override
public LocaleContext getValue() {
return LocaleContextHolder.getLocaleContext();
}
@Override
public void setValue(LocaleContext value) {
LocaleContextHolder.setLocaleContext(value);
}
@Override
public void setValue() {
LocaleContextHolder.resetLocaleContext();
}
}
public class RequestAttributesThreadLocalAccessor implements ThreadLocalAccessor<RequestAttributes> {
static final String KEY = "my-request-attributes";
@Override
public Object key() {
return KEY;
}
@Override
public RequestAttributes getValue() {
return RequestContextHolder.getRequestAttributes();
}
@Override
public void setValue(RequestAttributes value) {
RequestContextHolder.setRequestAttributes(value);
}
@Override
public void setValue() {
RequestContextHolder.resetRequestAttributes();
}
}
Comment From: dsyer
This looks useful to me. It won't work with an SSE controller method because the reactor context gets reset too early. Here an example: https://github.com/scratches/sse-render.
Comment From: snicoll
@ttddyy would you be interested to move that code snippet into an actual PR we can review (with the relevant doc and test). This targets main
and 6.2
. If not, no worries, we'll handle it.
Comment From: ttddyy
Yup, no problem. I'll create a PR for the change.
Comment From: snicoll
Closing in favor of PR #32243, thanks @ttddyy!
Comment From: dsyer
See also #32296 for a related bug.