Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure a custom source to feed Spring Boot's @ConfigurationProperties

I'm new to Spring Boot and reading about how @ConfigurationProperties annotation enables auto-injection of field values without @Value annotation.

@Configuration
@ConfigurationProperties(locations = "classpath:some.properties", prefix = "something")
public class MyConfiguration { .. }

I'd like to use Groovy's ConfigSlurper to read my property configuration. Is there a way to associate @ConfigurationProperties with a custom property reader, may be a custom extension of Spring class that deals with ConfigSlurper? Or is there a way to simulate the same behavior with a different feature?

like image 296
phanin Avatar asked May 27 '16 00:05

phanin


2 Answers

That's not what @ConfigurationProperties is meant to do. @ConfigurationProperties binds whatever is available from the Environment. The locations attribute is deprecated in 1.4 and will be removed in a future release.

The idea is that you specify a prefix and if they are keys matching that prefix in the environment, we inject the relevant properties in your POJO.If you want to use that infrastructure with this mechanism, please remove the locations attribute on the annotation and update the environment with your own property source. The other answer gives you a way to do that and you can use an EnvironmentPostProcessor to hook your implementation to the environment.

like image 140
Stephane Nicoll Avatar answered Oct 21 '22 23:10

Stephane Nicoll


You can do so by implementing your own PropertySourceLoader:

public class ConfigSlurperPropertySourceLoader implements PropertySourceLoader {

    @Override
    public String[] getFileExtensions() {
        return new String[] { "groovy" };
    }

    @Override
    public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
        ConfigObject source = new ConfigSlurper(profile).parse(resource.getURL());
        return new ConfigObjectPropertySource(name, source);
    }
}

Extending PropertySource<T> to read values from ConfigObject (the ConfigObjectPropertySource above). Then you register it inside META-INF/spring.factories:

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.example.ConfigSlurperPropertySourceLoader,\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

The spring-groovy-config already implements it and is available on github.

like image 44
miensol Avatar answered Oct 21 '22 22:10

miensol