3

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!

Schorsch
  • 203
  • 1
  • 2
  • 9

1 Answers1

3

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:

  • system properties
  • system environment variables

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247