Optional.of 期望纯值。您也可以在文档中找到信息,
/**
* Constructs an instance with the described value.
*
* @param value the non-{@code null} value to describe
* @throws NullPointerException if value is {@code null}
*/
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
例子,
jshell> Optional.of(100)
$2 ==> Optional[100]
jshell> Optional.of(null)
| Exception java.lang.NullPointerException
| at Objects.requireNonNull (Objects.java:221)
| at Optional.<init> (Optional.java:107)
| at Optional.of (Optional.java:120)
| at (#1:1)
如果你的值在运行时可以是null,你可以使用.ofNullable,
jshell> Optional.ofNullable(null)
$3 ==> Optional.empty
也
函数式编程的思想是为所有输入返回一个值,而不是抛出Exception,这会破坏函数组合。
jshell> Function<Integer, Optional<Integer>> f = x -> Optional.of(x + 1)
f ==> $Lambda$23/0x0000000801171c40@6996db8
jshell> Function<Integer, Optional<Integer>> g = x -> Optional.of(x * 2)
g ==> $Lambda$24/0x0000000801172840@7fbe847c
jshell> f.apply(5).flatMap(x -> g.apply(x))
$13 ==> Optional[12]
因此,在您的示例中,您可以将 Optional.empty() 视为未找到项目,但 Spring 也会将其视为 200,这仍然比抛出 500 更好。您可能想要发送404 准确。
@GetMapping(
value = "/compras",
produces = "application/json"
)
public Optional<Compras> retrieveAllCompras(@RequestParam String id) {
return Optional.ofNullable(compraRepository.findById(id)); //will response as 200 even when no item found
}
您可以使用ResponseEntity<A> to set specific http status
回复404 的传统方式是defining specific exception。
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
@GetMapping(
value = "/compras",
produces = "application/json"
)
public Compras retrieveAllCompras(@RequestParam String id) {
return Optional.ofNullable(compraRepository.findById(id))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "item not found"))
}