Be smarter about the ConfigClientProperties and parent context

In case there is a parent context we can re-use the bean from that
if it exists, instead of always creating it and risking the values
being different.
This commit is contained in:
Dave Syer
2015-01-16 14:03:12 +00:00
parent e2b4bea238
commit d8c7cc52fe
2 changed files with 40 additions and 1 deletions

View File

@@ -15,7 +15,9 @@
*/
package org.springframework.cloud.autoconfigure;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.cloud.config.client.ConfigClientProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@@ -33,7 +35,12 @@ import org.springframework.core.env.Environment;
public class ConfigClientAutoConfiguration {
@Bean
public ConfigClientProperties configClientProperties(Environment environment) {
public ConfigClientProperties configClientProperties(Environment environment,
ApplicationContext context) {
if (context.getParent()!=null && BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getParent(),
ConfigClientProperties.class).length > 0) {
return BeanFactoryUtils.beanOfType(context.getParent(), ConfigClientProperties.class);
}
ConfigClientProperties client = new ConfigClientProperties(environment);
return client;
}

View File

@@ -0,0 +1,32 @@
package org.springframework.cloud.autoconfigure;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.config.client.ConfigClientProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ConfigClientAutoConfigurationTests {
@Test
public void sunnyDay() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
ConfigClientAutoConfiguration.class);
assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
ConfigClientProperties.class).length);
context.close();
}
@Test
public void withParent() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.child(Object.class).web(false).run();
assertEquals(1, BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
ConfigClientProperties.class).length);
context.close();
}
}