Add support for binding to immutable collection
Fixes gh-9290
This commit is contained in:
@@ -51,9 +51,26 @@ class CollectionBinder extends IndexedElementsBinder<Collection<Object>> {
|
||||
@Override
|
||||
protected Collection<Object> merge(Collection<Object> existing,
|
||||
Collection<Object> additional) {
|
||||
existing.clear();
|
||||
existing.addAll(additional);
|
||||
return existing;
|
||||
try {
|
||||
existing.clear();
|
||||
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;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -289,4 +290,15 @@ public class CollectionBinderTests {
|
||||
List<String> values = result.stream().map(JavaBean::getValue).collect(Collectors.toList());
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user