Skip to content

Commit

Permalink
Add support for binding to immutable collection
Browse files Browse the repository at this point in the history
  • Loading branch information
mbhave committed May 23, 2017
1 parent db9ec87 commit 6c62936
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,26 @@ protected Object bind(ConfigurationPropertyName name, Bindable<?> target,
@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.");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -289,4 +290,15 @@ public void bindToNonScalarCollectionShouldReturnPopulatedCollection() throws Ex
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);
}

}

0 comments on commit 6c62936

Please sign in to comment.