在 Spring Boot RestController 中,我正在使用 springframework 类 ResponseEntity返回端点调用的响应。
我最近发现有两种方法可以实例化这个类。
使用构造函数:
response = new ResponseEntity<MyDto>(myDto, myHeaders, HttpStatus.OK);
使用静态构建器:
response = ResponseEntity.ok().headers(myHeaders).body(myDto);
生成的实例接缝是相同的。
我想知道,每个的优点和缺点是什么? 在什么情况下我应该优先使用其中之一?
最佳答案
使用构造函数,您必须提前构造它的参数,而使用构建器,您可以在一个流畅的语句中完成。
// constructor
MultiValueMap<String, String> headers = ...;
ResponseEntity<String> resp = new ResponseEntity(headers, HttpStatus.OK);
// builder
ResponseEntity<String> resp = ResponseEntity.ok()
.header("header1", "value1")
.header("header2", "value2")
.build();
此外,对于具有一长串参数的构造函数,很难看出每个参数的语义。在这些情况下,我更喜欢生成器。
关于java - Spring 响应实体 : use constructor or static builder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44151990/