Skip to content

Commit

Permalink
Avoid unnecessary creation of not-found entity in ResponseEntity#of
Browse files Browse the repository at this point in the history
  • Loading branch information
jhoeller authored and xcl(徐程林) committed Aug 16, 2020
1 parent 40bf12d commit 3ca5ad4
Showing 1 changed file with 16 additions and 18 deletions.
@@ -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.
Expand Down Expand Up @@ -217,19 +217,6 @@ public static BodyBuilder status(int status) {
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
Expand All @@ -246,8 +233,20 @@ public static BodyBuilder ok() {
* @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());
}

/**
Expand All @@ -258,8 +257,7 @@ public static <T> ResponseEntity<T> ok(T body) {
* @since 4.1
*/
public static BodyBuilder created(URI location) {
BodyBuilder builder = status(HttpStatus.CREATED);
return builder.location(location);
return status(HttpStatus.CREATED).location(location);
}

/**
Expand Down

0 comments on commit 3ca5ad4

Please sign in to comment.