#118 - Always default to fallback ConversionService in WebMvcLinkBuilder.

This commit is contained in:
Oliver Drotbohm
2021-03-11 14:44:46 +01:00
parent 8e78cf2275
commit 47486f42d7
2 changed files with 19 additions and 4 deletions

View File

@@ -148,15 +148,14 @@ public class WebMvcLinkBuilderFactory implements MethodLinkBuilderFactory<WebMvc
return WebMvcLinkBuilder.linkTo(method, parameters);
}
@SuppressWarnings("null")
private Supplier<ConversionService> getConversionService() {
private static Supplier<ConversionService> getConversionService() {
return () -> {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (!ServletRequestAttributes.class.isInstance(attributes)) {
return null;
if (attributes == null || !ServletRequestAttributes.class.isInstance(attributes)) {
return FALLBACK_CONVERSION_SERVICE;
}
ServletContext servletContext = ((ServletRequestAttributes) attributes).getRequest().getServletContext();

View File

@@ -38,6 +38,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
@@ -625,6 +626,14 @@ class WebMvcLinkBuilderUnitTest extends TestUtils {
assertThat(link.getHref()).endsWith("/api?view=short");
}
@Test // #118
void usesFallbackConversionServiceIfNoContextIsCurrentlyPresent() {
RequestContextHolder.setRequestAttributes(null);
linkTo(methodOn(ControllerWithHandlerMethodParameterThatNeedsConversion.class).method(41L)).withSelfRel();
}
private static UriComponents toComponents(Link link) {
return UriComponentsBuilder.fromUriString(link.expand().getHref()).build();
}
@@ -752,4 +761,11 @@ class WebMvcLinkBuilderUnitTest extends TestUtils {
return ResponseEntity.noContent().build();
}
}
// #???
interface ControllerWithHandlerMethodParameterThatNeedsConversion {
@GetMapping("/{id}")
HttpEntity<?> method(@PathVariable Long id);
}
}