Skip to content

Commit 7244f03

Browse files
committed
Avoid unnecessary creation of not-found entity in ResponseEntity#of
Closes gh-25183
1 parent 98030f3 commit 7244f03

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

spring-web/src/main/java/org/springframework/http/ResponseEntity.java

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2019 the original author or authors.
2+
* Copyright 2002-2020 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -217,19 +217,6 @@ public static BodyBuilder status(int status) {
217217
return new DefaultBuilder(status);
218218
}
219219

220-
/**
221-
* A shortcut for creating a {@code ResponseEntity} with the given body
222-
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
223-
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of an
224-
* {@linkplain Optional#empty()} parameter.
225-
* @return the created {@code ResponseEntity}
226-
* @since 5.1
227-
*/
228-
public static <T> ResponseEntity<T> of(Optional<T> body) {
229-
Assert.notNull(body, "Body must not be null");
230-
return body.map(ResponseEntity::ok).orElse(notFound().build());
231-
}
232-
233220
/**
234221
* Create a builder with the status set to {@linkplain HttpStatus#OK OK}.
235222
* @return the created builder
@@ -246,8 +233,20 @@ public static BodyBuilder ok() {
246233
* @since 4.1
247234
*/
248235
public static <T> ResponseEntity<T> ok(T body) {
249-
BodyBuilder builder = ok();
250-
return builder.body(body);
236+
return ok().body(body);
237+
}
238+
239+
/**
240+
* A shortcut for creating a {@code ResponseEntity} with the given body
241+
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
242+
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of an
243+
* {@linkplain Optional#empty()} parameter.
244+
* @return the created {@code ResponseEntity}
245+
* @since 5.1
246+
*/
247+
public static <T> ResponseEntity<T> of(Optional<T> body) {
248+
Assert.notNull(body, "Body must not be null");
249+
return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build());
251250
}
252251

253252
/**
@@ -258,8 +257,7 @@ public static <T> ResponseEntity<T> ok(T body) {
258257
* @since 4.1
259258
*/
260259
public static BodyBuilder created(URI location) {
261-
BodyBuilder builder = status(HttpStatus.CREATED);
262-
return builder.location(location);
260+
return status(HttpStatus.CREATED).location(location);
263261
}
264262

265263
/**

0 commit comments

Comments
 (0)