Reputation: 323
I love the Spring properties loading mechanism. The fact that you can define several profiles and override or extend properties with other profiles, that you can use different file types (.properties, XML, JSON, ...) to store your properties, that you can use the value of other properties to resolve its own value, aso.
But to use the properties, you have to somehow initialize the Spring context (@SpringBootApplication or @SpringBootTest). And I would like to use this property loading mechanism in some libraries, where I cannot guarantee that the context is loaded (and I do not want to load it).
So, my question:
Can I somehow create a class that uses the Spring libraries to load the properties (on demand) in the same way Spring loads its properties?
Other classes will then use this class to access the properties. No need to load with annotations.
I was searching for this for some time, but I haven't found a solution, yet.
Would be great if so. knows a solution for that.
Regards, stay healthy and merry X-Mas!
Upvotes: 3
Views: 1480
Reputation: 11
It's a quite dated question, but I recently came across similar problem and with current versions of Spring, you can achieve this simply by initiating a Spring Environment
and then using a ConfigDataEnvironmentPostProcessor
(which replaced a now deprecated ConfigFileApplicationListener
) to apply all the default post processing in regards to external configuration.
ConfigurableEnvironment env = new StandardEnvironment();
ConfigDataEnvironmentPostProcessor.applyTo(env);
Although I haven't checked all the features, the post-processed environment properly resolved all configuration files, considering spring-profiles, as you'd normally expect.
Upvotes: 1
Reputation: 159086
The property lookup mechanism is defined by interface PropertyResolver
, extended by interface Environment
to support profiles, further extended by interface ConfigurableEnvironment
to support PropertySources
, i.e. the concept of searching through a set of property sources to find a property.
It is implemented e.g. by class StandardEnvironment
, which defines property source for:
All the above are part of package org.springframework.core.env
, i.e. part of the spring-core-XXX.jar
file.
Support for application.properties
files is added by class ConfigFileApplicationListener
in package org.springframework.boot.context.config
.
The class needs an instance of SpringApplication
in package org.springframework.boot
.
They are part of the spring-boot-XXX.jar
file.
So, getting basic Spring property support is easy, just create a StandardEnvironment
object.
Getting application.properties
files loaded is deeply embedded in the Spring Boot code, and would be really difficult to do without initializing the Spring context.
Upvotes: 4