Skip to content

Commit c2d1cb2

Browse files
ayudovinphilwebb
authored andcommitted
Chain predicates in PropertyMapper when methods
Update `PropertyMapper` to correctly combine predicates when repeated calls are made to `when` and `whenNot`. Prior to this commit, subsequent invocations would replace the previous predicate. Fixes gh-17225
1 parent 88fbc52 commit c2d1cb2

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
* {@link Source#toInstance(Function) new instance}.
5151
*
5252
* @author Phillip Webb
53+
* @author Artsiom Yudovin
5354
* @since 2.0.0
5455
*/
5556
public final class PropertyMapper {
@@ -288,7 +289,7 @@ public <R extends T> Source<R> whenInstanceOf(Class<R> target) {
288289
*/
289290
public Source<T> whenNot(Predicate<T> predicate) {
290291
Assert.notNull(predicate, "Predicate must not be null");
291-
return new Source<>(this.supplier, predicate.negate());
292+
return when(predicate.negate());
292293
}
293294

294295
/**
@@ -299,7 +300,7 @@ public Source<T> whenNot(Predicate<T> predicate) {
299300
*/
300301
public Source<T> when(Predicate<T> predicate) {
301302
Assert.notNull(predicate, "Predicate must not be null");
302-
return new Source<>(this.supplier, predicate);
303+
return new Source<>(this.supplier, (this.predicate != null) ? this.predicate.and(predicate) : predicate);
303304
}
304305

305306
/**

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
* Tests for {@link PropertyMapper}.
2929
*
3030
* @author Phillip Webb
31+
* @author Artsiom Yudovin
3132
*/
3233
public class PropertyMapperTests {
3334

@@ -190,6 +191,17 @@ public void whenWhenCombinedWithAsUsesSourceValue() {
190191
assertThat(source.getCount()).isOne();
191192
}
192193

194+
@Test
195+
public void whenWhenValueNotMatchesShouldSupportChainedCalls() {
196+
this.map.from("123").when("456"::equals).when("123"::equals).toCall(Assert::fail);
197+
}
198+
199+
@Test
200+
public void whenWhenValueMatchesShouldSupportChainedCalls() {
201+
String result = this.map.from("123").when((s) -> s.contains("2")).when("123"::equals).toInstance(String::new);
202+
assertThat(result).isEqualTo("123");
203+
}
204+
193205
@Test
194206
public void alwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() {
195207
this.map.alwaysApplyingWhenNonNull().from(() -> null).toCall(Assert::fail);

0 commit comments

Comments
 (0)