I am interested in creating one or more custom property source loaders and using those property sources with @ConfigurationProperties
in my application.
For example, I would like to develop a property source loader capable of loading an XML file and converting it into a set of properties that can be injected into my @Configuration
annotated classes.
@Configuration
@ConfigurationProperties(locations="classpath:config.xml")
public class MyConfig
{
...
}
Is any such XML-based property source loader publicly available? If not, then how would I go about making it available to my application once I have it implemented?
Thank you.
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.
@ConfigurationProperties allows to map the entire Properties and Yaml files into an object easily. It also allows to validate properties with JSR-303 bean validation. By default, the annotation reads from the application. properties file. The source file can be changed with @PropertySource annotation.
You can check YamlPropertySourceLoader how it is implemented. Once you implement it method
org.springframework.boot.env.YamlPropertySourceLoader#getFileExtensions
will be called once you add something like this
@ConfigurationProperties(locations="classpath:config.xml")
But watching implementation of YamlPropertySourceLoader it looks like you will have a lot of work to do, with paring etc.
You should check if yaml will be sufficient for you because it gives you possibility to make structured properties:
For example, the following YAML document:
environments:
dev:
url: http://dev.bar.com
name: Developer Setup
prod:
url: http://foo.bar.com
name: My Cool App
Would be transformed into these properties:
environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
YAML lists are represented as property keys with [index] dereferencers, for example this YAML:
my:
servers:
- dev.bar.com
- foo.bar.com
Would be transformed into these properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
Even if you have XML docs ready and that is reason you want to load them in configuration it looks much more simple to convert XML to YAML (https://github.com/FasterXML/jackson-dataformat-xml) and than using existing YamlPropertySourceLoader than to write your own PropertySourceLoader.
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