Avoid unnecessary creation of not-found entity in ResponseEntity#of

Closes gh-25183
This commit is contained in:
Juergen Hoeller
2020-06-06 17:44:30 +02:00
parent 98030f3794
commit 7244f03064

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -217,19 +217,6 @@ public class ResponseEntity<T> extends HttpEntity<T> {
return new DefaultBuilder(status);
}
/**
* A shortcut for creating a {@code ResponseEntity} with the given body
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of an
* {@linkplain Optional#empty()} parameter.
* @return the created {@code ResponseEntity}
* @since 5.1
*/
public static <T> ResponseEntity<T> of(Optional<T> body) {
Assert.notNull(body, "Body must not be null");
return body.map(ResponseEntity::ok).orElse(notFound().build());
}
/**
* Create a builder with the status set to {@linkplain HttpStatus#OK OK}.
* @return the created builder
@@ -246,8 +233,20 @@ public class ResponseEntity<T> extends HttpEntity<T> {
* @since 4.1
*/
public static <T> ResponseEntity<T> ok(T body) {
BodyBuilder builder = ok();
return builder.body(body);
return ok().body(body);
}
/**
* A shortcut for creating a {@code ResponseEntity} with the given body
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of an
* {@linkplain Optional#empty()} parameter.
* @return the created {@code ResponseEntity}
* @since 5.1
*/
public static <T> ResponseEntity<T> of(Optional<T> body) {
Assert.notNull(body, "Body must not be null");
return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build());
}
/**
@@ -258,8 +257,7 @@ public class ResponseEntity<T> extends HttpEntity<T> {
* @since 4.1
*/
public static BodyBuilder created(URI location) {
BodyBuilder builder = status(HttpStatus.CREATED);
return builder.location(location);
return status(HttpStatus.CREATED).location(location);
}
/**