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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With