在 Spring Boot 2.3 中复制 Spring 数据 Rest 搜索控制器
Reproducing Spring Data Rest search controllers in Spring Boot 2.3
在 Spring Boot 2.0 之前,我可以重现为 mongodb 存储库公开的查询方法生成的控制器。
这是一个代码示例:
域实体
@Document(collection = "foos")
public class Foo {
@Id
private String id;
private String name;
// getters/setters omitted
}
Mongo 存储库
public interface FooRepository extends MongoRepository<Foo, String> {
public Page<Foo> findByName(@Param("name") String name, Pageable pageable);
}
Spring Boot通过/foos/search/findByName?name=...
自动暴露搜索方法,结果类似这样:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/findByName?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
我可以使用以下自定义控制器和配置重现它
@RestController
@RequestMapping("foos")
@RequiredArgsConstructor // lombok
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
@GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_UT8_VALUE)
public ResponseEntity custom(@RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toResource(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
// Enables injecting a PersistentEntityResourceAssembler in a RestController
// see https://jira.spring.io/browse/DATAREST-657 for details
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class MvcConfiguration implements WebMvcConfigurer {
// WARNING: do NOT change the name of this member - it is injected with the
// RequestMappingHandlerAdapter$repositoryExporterHandlerAdapter().
private final RequestMappingHandlerAdapter repositoryExporterHandlerAdapter;
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
List<HandlerMethodArgumentResolver> customArgumentResolvers =
repositoryExporterHandlerAdapter.getCustomArgumentResolvers();
argumentResolvers.addAll(customArgumentResolvers);
}
}
有了这个,我可以向 /foos/search/query?name=...
发送请求并获得预期的响应:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/query?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
切换到 Spring Boot 2.3,在控制器中使用 Spring HATEOAS 1.0 API
@RestController
@RequestMapping("foos")
@RequiredArgsConstructor
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
@GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity custom(@RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toModel(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
我现在得到以下结果:
{"_embedded":{"foos":[{"id":"56a8a8d5daffd28c9c907974","name":"qc","embeddeds":{},"nested":false,"persistentEntity":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":
Spring 的日志中出现以下错误:
2020-08-06 18:11:20.968 WARN 9932 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failure while trying to resolve exception [org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:472) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.sendServerError(DefaultHandlerExceptionResolver.java:550) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(DefaultHandlerExceptionResolver.java:440) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException(DefaultHandlerExceptionResolver.java:210) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:141) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:80) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1300) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1111) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-08-06 18:11:20.979 ERROR 9932 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (WhosebugError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (WhosebugError) (through reference chain: org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]-> ... IT GOES ON AND ON LIKE THIS ... ->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"])] with root cause
java.lang.WhosebugError: null
at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na]
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) ~[na:na]
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:773) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
... IT GOES ON LIKE THIS FOR DOZENS AND DOZENS OF LINE
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
2020-08-06 18:11:21.553 ERROR 9932 --- [nio-8080-exec-1] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/foos/search/query] and exception [] as the response has already been committed. As a result, the response may have the wrong status code.
If if return var page = repository.findByName(name, pageable);
而不是 var model = pagedResourcesAssembler.toModel(page, resourceAssembler);
的内容,我得到以下结果:
{"content":[{"id":"56a8a8d5daffd28c9c907974","name":"qc"}],"pageable":{"sort":{"sorted":false,"unsorted":true,"empty":true},"offset":0,"pageNumber":0,"pageSize":20,"paged":true,"unpaged":false},"last":true,"totalPages":1,"totalElements":1,"size":20,"number":0,"sort":{"sorted":false,"unsorted":true,"empty":true},"numberOfElements":1,"first":true,"empty":false}
所以循环混乱来自序列化 pagedResourcesAssembler.toModel(page, resourceAssembler)
(可能还有 WebMvcConfigurer 覆盖)。
当我调用 PersistentEntityResourceAssembler.toModel(Object)
时,我有相同的 WhosebugError: null
。我的代码 returns 是一个 EntityModel
而不是 PagedModel
。我的问题通过切换到 PersistentEntityResourceAssembler.toFullResource(Object)
.
得到解决
toModel(Object)
使用摘录投影,而 toFullResource(Object)
不使用。我没有时间深入研究代码来检查是什么产生了无限循环导致堆栈溢出。
查看PagedResourcesAssembler
的源代码,PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler)
调用RepresentationModelAssember.toModel(Object)
。
所以解决方法 1 是复制 PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler)
的源代码并使用 RepresentationModelAssember.toFullResource(Object)
.
解决方法 2 是扩展 PagedResourcesAssembler
并覆盖 createModel(...)
方法。
在解决问题之前,我有一个问题。为什么要将 PersistentEntityResourceAssembler
传递给 PagedResourcesAssembler
?当我的自定义控制器 returns 单个资源时,我的代码使用 PersistentEntityResourceAssembler
添加 HTTP headers ETag
和 Last-Modified
。使用PersistentEntityResourceAssembler
构建collection资源(分页资源)的响应有什么好处?
感谢 this thread on Spring JIRA,我能够:
- 将控制器
MultiValueMap
参数转换为 Predicate
- 使用
RepositoryRestController
而不是 RestController
,即能够将 PersistentEntityResourceAssembler
注入控制器方法。
已接受的答案中建议的自定义模型和模型组装器不是必需的。
配置一个QuerydslPredicateBuilder
bean:
@Configuration
@RequiredArgsConstructor
public class QueryDslConfiguration {
private final ConversionService mvcConversionService;
private final QuerydslBindingsFactory querydslBindingsFactory;
@Bean
public QuerydslPredicateBuilder querydslPredicateBuilder() {
return new QuerydslPredicateBuilder(mvcConversionService, querydslBindingsFactory.getEntityPathResolver());
}
}
将 MultiValueMap 转换为 Predicate 的服务:
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PredicateService {
private final QuerydslPredicateBuilder querydslPredicateBuilder;
private final QuerydslBindingsFactory querydslBindingsFactory;
public <T> Predicate getPredicateFromParameters(final MultiValueMap<String, String> parameters, Class<T> tClass) {
TypeInformation<T> typeInformation = ClassTypeInformation.from(tClass);
return querydslPredicateBuilder.getPredicate(typeInformation,
parameters,
querydslBindingsFactory.createBindingsFor(typeInformation));
}
}
在控制器中使用转换器:
@RepositoryRestController
@RequiredArgsConstructor
public class FooController {
private final FooRepository repository;
private final PredicateService predicateService;
@GetMapping("/foos/search/query")
public PagedModel<Foo> query(
@RequestParam MultiValueMap<String, String> parameters,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
Predicate predicate = predicateService.getPredicateFromParameters(parameters, Foo.class);
Page<Parameter> page = repository.findAll(predicate,
return pagedResourcesAssembler.toModel(page, resourceAssembler);
}
}
在 Spring Boot 2.0 之前,我可以重现为 mongodb 存储库公开的查询方法生成的控制器。 这是一个代码示例:
域实体
@Document(collection = "foos")
public class Foo {
@Id
private String id;
private String name;
// getters/setters omitted
}
Mongo 存储库
public interface FooRepository extends MongoRepository<Foo, String> {
public Page<Foo> findByName(@Param("name") String name, Pageable pageable);
}
Spring Boot通过/foos/search/findByName?name=...
自动暴露搜索方法,结果类似这样:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/findByName?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
我可以使用以下自定义控制器和配置重现它
@RestController
@RequestMapping("foos")
@RequiredArgsConstructor // lombok
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
@GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_UT8_VALUE)
public ResponseEntity custom(@RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toResource(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
// Enables injecting a PersistentEntityResourceAssembler in a RestController
// see https://jira.spring.io/browse/DATAREST-657 for details
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class MvcConfiguration implements WebMvcConfigurer {
// WARNING: do NOT change the name of this member - it is injected with the
// RequestMappingHandlerAdapter$repositoryExporterHandlerAdapter().
private final RequestMappingHandlerAdapter repositoryExporterHandlerAdapter;
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
List<HandlerMethodArgumentResolver> customArgumentResolvers =
repositoryExporterHandlerAdapter.getCustomArgumentResolvers();
argumentResolvers.addAll(customArgumentResolvers);
}
}
有了这个,我可以向 /foos/search/query?name=...
发送请求并获得预期的响应:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/query?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
切换到 Spring Boot 2.3,在控制器中使用 Spring HATEOAS 1.0 API
@RestController
@RequestMapping("foos")
@RequiredArgsConstructor
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
@GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity custom(@RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toModel(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
我现在得到以下结果:
{"_embedded":{"foos":[{"id":"56a8a8d5daffd28c9c907974","name":"qc","embeddeds":{},"nested":false,"persistentEntity":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":
Spring 的日志中出现以下错误:
2020-08-06 18:11:20.968 WARN 9932 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failure while trying to resolve exception [org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:472) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.sendServerError(DefaultHandlerExceptionResolver.java:550) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(DefaultHandlerExceptionResolver.java:440) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException(DefaultHandlerExceptionResolver.java:210) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:141) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:80) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1300) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1111) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-08-06 18:11:20.979 ERROR 9932 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (WhosebugError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (WhosebugError) (through reference chain: org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]-> ... IT GOES ON AND ON LIKE THIS ... ->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"])] with root cause
java.lang.WhosebugError: null
at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na]
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) ~[na:na]
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:773) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
... IT GOES ON LIKE THIS FOR DOZENS AND DOZENS OF LINE
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
2020-08-06 18:11:21.553 ERROR 9932 --- [nio-8080-exec-1] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/foos/search/query] and exception [] as the response has already been committed. As a result, the response may have the wrong status code.
If if return var page = repository.findByName(name, pageable);
而不是 var model = pagedResourcesAssembler.toModel(page, resourceAssembler);
的内容,我得到以下结果:
{"content":[{"id":"56a8a8d5daffd28c9c907974","name":"qc"}],"pageable":{"sort":{"sorted":false,"unsorted":true,"empty":true},"offset":0,"pageNumber":0,"pageSize":20,"paged":true,"unpaged":false},"last":true,"totalPages":1,"totalElements":1,"size":20,"number":0,"sort":{"sorted":false,"unsorted":true,"empty":true},"numberOfElements":1,"first":true,"empty":false}
所以循环混乱来自序列化 pagedResourcesAssembler.toModel(page, resourceAssembler)
(可能还有 WebMvcConfigurer 覆盖)。
当我调用 PersistentEntityResourceAssembler.toModel(Object)
时,我有相同的 WhosebugError: null
。我的代码 returns 是一个 EntityModel
而不是 PagedModel
。我的问题通过切换到 PersistentEntityResourceAssembler.toFullResource(Object)
.
toModel(Object)
使用摘录投影,而 toFullResource(Object)
不使用。我没有时间深入研究代码来检查是什么产生了无限循环导致堆栈溢出。
查看PagedResourcesAssembler
的源代码,PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler)
调用RepresentationModelAssember.toModel(Object)
。
所以解决方法 1 是复制 PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler)
的源代码并使用 RepresentationModelAssember.toFullResource(Object)
.
解决方法 2 是扩展 PagedResourcesAssembler
并覆盖 createModel(...)
方法。
在解决问题之前,我有一个问题。为什么要将 PersistentEntityResourceAssembler
传递给 PagedResourcesAssembler
?当我的自定义控制器 returns 单个资源时,我的代码使用 PersistentEntityResourceAssembler
添加 HTTP headers ETag
和 Last-Modified
。使用PersistentEntityResourceAssembler
构建collection资源(分页资源)的响应有什么好处?
感谢 this thread on Spring JIRA,我能够:
- 将控制器
MultiValueMap
参数转换为Predicate
- 使用
RepositoryRestController
而不是RestController
,即能够将PersistentEntityResourceAssembler
注入控制器方法。
已接受的答案中建议的自定义模型和模型组装器不是必需的。
配置一个QuerydslPredicateBuilder
bean:
@Configuration
@RequiredArgsConstructor
public class QueryDslConfiguration {
private final ConversionService mvcConversionService;
private final QuerydslBindingsFactory querydslBindingsFactory;
@Bean
public QuerydslPredicateBuilder querydslPredicateBuilder() {
return new QuerydslPredicateBuilder(mvcConversionService, querydslBindingsFactory.getEntityPathResolver());
}
}
将 MultiValueMap 转换为 Predicate 的服务:
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PredicateService {
private final QuerydslPredicateBuilder querydslPredicateBuilder;
private final QuerydslBindingsFactory querydslBindingsFactory;
public <T> Predicate getPredicateFromParameters(final MultiValueMap<String, String> parameters, Class<T> tClass) {
TypeInformation<T> typeInformation = ClassTypeInformation.from(tClass);
return querydslPredicateBuilder.getPredicate(typeInformation,
parameters,
querydslBindingsFactory.createBindingsFor(typeInformation));
}
}
在控制器中使用转换器:
@RepositoryRestController
@RequiredArgsConstructor
public class FooController {
private final FooRepository repository;
private final PredicateService predicateService;
@GetMapping("/foos/search/query")
public PagedModel<Foo> query(
@RequestParam MultiValueMap<String, String> parameters,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
Predicate predicate = predicateService.getPredicateFromParameters(parameters, Foo.class);
Page<Parameter> page = repository.findAll(predicate,
return pagedResourcesAssembler.toModel(page, resourceAssembler);
}
}