Skip to content

Commit fe554ff

Browse files
committed
Merge pull request #50773 from xfocus3
Closes gh-50773 * pr/50773: Polish 'Bind empty strings to empty maps' Bind empty strings to empty maps
2 parents f71e797 + 12eb466 commit fe554ff

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

  • core/spring-boot/src

core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
*
4040
* @author Phillip Webb
4141
* @author Madhura Bhave
42+
* @author Ahmed El Amraouiyine
4243
*/
4344
class MapBinder extends AggregateBinder<Map<Object, Object>> {
4445

@@ -64,6 +65,9 @@ protected boolean isAllowRecursiveBinding(@Nullable ConfigurationPropertySource
6465
if (property != null) {
6566
getContext().setConfigurationProperty(property);
6667
Object result = getContext().getPlaceholdersResolver().resolvePlaceholders(property.getValue());
68+
if (result instanceof CharSequence charSequence && charSequence.isEmpty()) {
69+
return createMap(target);
70+
}
6771
return getContext().getConverter().convert(result, target);
6872
}
6973
}

core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
*
6666
* @author Phillip Webb
6767
* @author Madhura Bhave
68+
* @author Ahmed El Amraouiyine
6869
*/
6970
class MapBinderTests {
7071

@@ -274,6 +275,15 @@ void bindToMapWhenNoValueShouldReturnUnbound() {
274275
assertThat(result.isBound()).isFalse();
275276
}
276277

278+
@Test
279+
void bindToMapWhenEmptyStringShouldReturnEmptyMap() {
280+
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
281+
source.put("foo", "");
282+
this.sources.add(source);
283+
Map<String, String> result = this.binder.bind("foo", STRING_STRING_MAP).get();
284+
assertThat(result).isEmpty();
285+
}
286+
277287
@Test
278288
void bindToMapShouldConvertKey() {
279289
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
@@ -510,6 +520,17 @@ void nestedMapsShouldNotBindToNull() {
510520
assertThat(foo2.getValue()).isEqualTo("three");
511521
}
512522

523+
@Test
524+
void nestedMapsWhenEmptyStringShouldReturnEmptyMap() {
525+
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
526+
source.put("foo.value", "one");
527+
source.put("foo.foos", "");
528+
this.sources.add(source);
529+
BindResult<NestableFoo> foo = this.binder.bind("foo", NestableFoo.class);
530+
assertThat(foo.get().getValue()).isEqualTo("one");
531+
assertThat(foo.get().getFoos()).isEmpty();
532+
}
533+
513534
@Test
514535
void bindToMapWithCustomConverter() {
515536
DefaultConversionService conversionService = new DefaultConversionService();

0 commit comments

Comments
 (0)