[bs-22] Move @ConfigurationProperties processing to main jar

Also add unit tests.  Note also the start.groovy for the service
sample now works.

[#48127729]
This commit is contained in:
Dave Syer
2013-05-01 14:01:13 +01:00
parent 89748028b4
commit bd79ec2362
11 changed files with 151 additions and 23 deletions

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.bootstrap.context.annotation;
import java.lang.reflect.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.bootstrap.bind.PropertySourcesBindingPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
/**
* Configuration for binding externalized application properties to
* {@link ConfigurationProperties} beans.
*
* @author Dave Syer
*/
@Configuration
public class ConfigurationPropertiesBindingConfiguration {
@Autowired(required = false)
private PropertySourcesPlaceholderConfigurer configurer;
@Autowired(required = false)
private Environment environment;
@Autowired(required = false)
@Qualifier(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME)
private ConversionService conversionService;
/**
* Lifecycle hook that binds application properties to any bean whose type is
* decorated with {@link ConfigurationProperties} annotation.
*
* @return a bean post processor to bind application properties
*/
@Bean
public PropertySourcesBindingPostProcessor propertySourcesBinder() {
PropertySources propertySources;
if (this.configurer != null) {
propertySources = extractPropertySources(this.configurer);
} else {
if (this.environment instanceof ConfigurableEnvironment) {
propertySources = flattenPropertySources(((ConfigurableEnvironment) this.environment)
.getPropertySources());
} else {
// empty, so not very useful, but fulfils the contract
propertySources = new MutablePropertySources();
}
}
PropertySourcesBindingPostProcessor processor = new PropertySourcesBindingPostProcessor();
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
processor.setValidator(validator);
processor.setConversionService(this.conversionService);
processor.setPropertySources(propertySources);
return processor;
}
/**
* Flatten out a tree of property sources.
*
* @param propertySources some PropertySources, possibly containing environment
* properties
* @return another PropertySources containing the same properties
*/
private PropertySources flattenPropertySources(PropertySources propertySources) {
MutablePropertySources result = new MutablePropertySources();
for (PropertySource<?> propertySource : propertySources) {
flattenPropertySources(propertySource, result);
}
return result;
}
/**
* Convenience method to allow recursive flattening of property sources.
*
* @param propertySource a property source to flatten
* @param result the cumulative result
*/
private void flattenPropertySources(PropertySource<?> propertySource,
MutablePropertySources result) {
Object source = getField(propertySource, "source");
if (source instanceof ConfigurableEnvironment) {
ConfigurableEnvironment environment = (ConfigurableEnvironment) source;
for (PropertySource<?> childSource : environment.getPropertySources()) {
flattenPropertySources(childSource, result);
}
} else {
result.addLast(propertySource);
}
}
/**
* Convenience method to extract PropertySources from an existing (and already
* initialized) PropertySourcesPlaceholderConfigurer. As long as this method is
* executed late enough in the context lifecycle it will come back with data. We can
* rely on the fact that PropertySourcesPlaceholderConfigurer is a
* BeanFactoryPostProcessor and is therefore initialized early.
*
* @param configurer a PropertySourcesPlaceholderConfigurer
* @return some PropertySources
*/
private PropertySources extractPropertySources(
PropertySourcesPlaceholderConfigurer configurer) {
PropertySources propertySources = (PropertySources) getField(configurer,
"propertySources");
// Flatten the sources into a single list so they can be iterated
return flattenPropertySources(propertySources);
}
private Object getField(Object target, String name) {
// Hack, hack, hackety, hack...
Field field = ReflectionUtils.findField(target.getClass(), name);
ReflectionUtils.makeAccessible(field);
return ReflectionUtils.getField(field, target);
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.bootstrap.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* @author Dave Syer
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesImportSelector.class)
public @interface EnableConfigurationProperties {
Class<?>[] value() default {};
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.bootstrap.context.annotation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.MultiValueMap;
/**
* Import selector that sets up binding of external properties to configuration classes
* (see {@link ConfigurationProperties}). It either registers a
* {@link ConfigurationProperties} bean or not, depending on whether the enclosing
* {@link EnableConfigurationProperties} explicitly declares one. If none is declared then
* a bean post processor will still kick in for any beans annotated as external
* configuration. If one is declared then it a bean definition is registered with id equal
* to the class name (thus an application context usually only contains one
* {@link ConfigurationProperties} bean of each unique type).
*
* @author Dave Syer
*/
public class EnableConfigurationPropertiesImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata metadata) {
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(
EnableConfigurationProperties.class.getName(), false);
Object[] type = (Object[]) attributes.getFirst("value");
if (type == null || type.length == 0) {
return new String[] { ConfigurationPropertiesBindingConfiguration.class
.getName() };
}
return new String[] { ConfigurationPropertiesBeanRegistrar.class.getName(),
ConfigurationPropertiesBindingConfiguration.class.getName() };
}
public static class ConfigurationPropertiesBeanRegistrar implements
ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
MultiValueMap<String, Object> attributes = metadata
.getAllAnnotationAttributes(
EnableConfigurationProperties.class.getName(), false);
List<Class<?>> types = collectClasses(attributes.get("value"));
for (Class<?> type : types) {
registry.registerBeanDefinition(type.getName(), BeanDefinitionBuilder
.genericBeanDefinition(type).getBeanDefinition());
}
}
private List<Class<?>> collectClasses(List<Object> list) {
ArrayList<Class<?>> result = new ArrayList<Class<?>>();
for (Object object : list) {
for (Object value : (Object[]) object) {
if (value instanceof Class && value != void.class) {
result.add((Class<?>) value);
}
}
}
return result;
}
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.bootstrap.context.annotation;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class EnableConfigurationPropertiesTests {
private AnnotationConfigApplicationContext context;
@Before
public void open() throws Exception {
this.context = new AnnotationConfigApplicationContext();
this.context
.getEnvironment()
.getPropertySources()
.addFirst(
new PropertiesPropertySource("props",
getProperties("external.name=foo\nanother.name=bar")));
}
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void testSimpleAutoConfig() throws Exception {
this.context.register(ExampleConfig.class);
this.context.refresh();
assertEquals("foo", this.context.getBean(External.class).getName());
}
@Test
public void testExplicitType() throws Exception {
this.context.register(AnotherExampleConfig.class);
this.context.refresh();
assertEquals("foo", this.context.getBean(External.class).getName());
}
@Test
public void testMultipleExplicitTypes() throws Exception {
this.context.register(FurtherExampleConfig.class);
this.context.refresh();
assertEquals("foo", this.context.getBean(External.class).getName());
assertEquals("bar", this.context.getBean(Another.class).getName());
}
private Properties getProperties(String values) throws Exception {
return PropertiesLoaderUtils.loadProperties(new ByteArrayResource(values
.getBytes()));
}
@EnableConfigurationProperties
@Configuration
public static class ExampleConfig {
@Bean
public External external() {
return new External();
}
}
@EnableConfigurationProperties(External.class)
@Configuration
public static class AnotherExampleConfig {
}
@EnableConfigurationProperties({ External.class, Another.class })
@Configuration
public static class FurtherExampleConfig {
}
@ConfigurationProperties(name = "external")
public static class External {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
@ConfigurationProperties(name = "another")
public static class Another {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}