简体   繁体   中英

Use Spring properties loading without initializing the Spring context

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!

The property lookup mechanism is defined by interface PropertyResolver , extended by interface Environment to support profiles , further extended by interface ConfigurableEnvironment to support PropertySources , ie the concept of searching through a set of property sources to find a property.

It is implemented eg by class StandardEnvironment , which defines property source for:

  • system properties
  • system environment variables

All the above are part of package org.springframework.core.env , ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM