Brandon E Taylor
Brandon E Taylor

Reputation: 25339

Custom XML-Based Property Source Loader for Use With @ConfigurationProperties

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.

Upvotes: 8

Views: 1140

Answers (1)

mommcilo
mommcilo

Reputation: 946

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.

Upvotes: 4

Related Questions