Commit 05d2ca4f authored by Phillip Webb's avatar Phillip Webb

Allow bean binding if property binding fails

Update `Binder` so that if a property exists, but it cannot be converted
to required type, bean binding is attempted.

Prior to this commit, if a user happened to have an environment
variable named `SERVER` the binder would fail when trying to directly
convert its `String` value into a `ServerProperties`

Fixes gh-10945
parent 93ae71cf
......@@ -38,6 +38,7 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyS
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.context.properties.source.ConfigurationPropertyState;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.env.Environment;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.util.Assert;
......@@ -244,7 +245,18 @@ public class Binder {
return bindAggregate(name, target, handler, context, aggregateBinder);
}
if (property != null) {
return bindProperty(name, target, handler, context, property);
try {
return bindProperty(name, target, handler, context, property);
}
catch (ConverterNotFoundException ex) {
// We might still be able to bind it as a bean
Object bean = bindBean(name, target, handler, context,
allowRecursiveBinding);
if (bean != null) {
return bean;
}
throw ex;
}
}
return bindBean(name, target, handler, context, allowRecursiveBinding);
}
......
......@@ -190,6 +190,18 @@ public class BinderTests {
assertThat(result.getValue()).isEqualTo("bar");
}
@Test
public void bindToJavaBeanWhenHasPropertyWithSameNameShouldStillBind()
throws Exception {
// gh-10945
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
source.put("foo", "boom");
source.put("foo.value", "bar");
this.sources.add(source);
JavaBean result = this.binder.bind("foo", Bindable.of(JavaBean.class)).get();
assertThat(result.getValue()).isEqualTo("bar");
}
@Test
public void bindToJavaBeanShouldTriggerOnSuccess() throws Exception {
this.sources
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment