Add support for binding to immutable collection

Fixes gh-9290
pull/8534/merge
Madhura Bhave 8 years ago
parent db9ec87b14
commit 6c629369d3

@ -51,9 +51,26 @@ class CollectionBinder extends IndexedElementsBinder<Collection<Object>> {
@Override @Override
protected Collection<Object> merge(Collection<Object> existing, protected Collection<Object> merge(Collection<Object> existing,
Collection<Object> additional) { Collection<Object> additional) {
existing.clear(); try {
existing.addAll(additional); existing.clear();
return existing; existing.addAll(additional);
return existing;
}
catch (UnsupportedOperationException ex) {
return createNewCollection(additional);
}
}
@SuppressWarnings("unchecked")
private Collection<Object> createNewCollection(Collection<Object> additional) {
try {
Collection<Object> merged = additional.getClass().newInstance();
merged.addAll(additional);
return merged;
}
catch (Exception e) {
throw new IllegalStateException("Adding bound values to collection failed.");
}
} }
} }

@ -17,6 +17,7 @@
package org.springframework.boot.context.properties.bind; package org.springframework.boot.context.properties.bind;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -289,4 +290,15 @@ public class CollectionBinderTests {
List<String> values = result.stream().map(JavaBean::getValue).collect(Collectors.toList()); List<String> values = result.stream().map(JavaBean::getValue).collect(Collectors.toList());
assertThat(values).containsExactly("a", "b", "c"); assertThat(values).containsExactly("a", "b", "c");
} }
@Test
public void bindToImmutableCollectionShouldReturnPopulatedCollection() throws Exception {
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
source.put("foo.values", "a,b,c");
this.sources.add(source);
Set<String> result = this.binder.bind("foo.values",
STRING_SET.withExistingValue(Collections.emptySet())).get();
assertThat(result).hasSize(3);
}
} }

Loading…
Cancel
Save