From 3ca5ad412b45ab811c9c9b938b05cfd63cf75269 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sat, 6 Jun 2020 17:44:30 +0200 Subject: [PATCH] Avoid unnecessary creation of not-found entity in ResponseEntity#of Closes gh-25183 --- .../springframework/http/ResponseEntity.java | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/ResponseEntity.java b/spring-web/src/main/java/org/springframework/http/ResponseEntity.java index 9e07f703f435..f9df9eb3a160 100644 --- a/spring-web/src/main/java/org/springframework/http/ResponseEntity.java +++ b/spring-web/src/main/java/org/springframework/http/ResponseEntity.java @@ -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 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 ResponseEntity of(Optional 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 static BodyBuilder ok() { * @since 4.1 */ public static ResponseEntity 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 ResponseEntity of(Optional body) { + Assert.notNull(body, "Body must not be null"); + return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build()); } /** @@ -258,8 +257,7 @@ public static ResponseEntity 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); } /**