Home > Enterprise >  Spring boot - Loading configuration property file in to java.util.properties
Spring boot - Loading configuration property file in to java.util.properties

Time:05-09

I need to load a configuration property fully into java.util.Properties file in my spring boot project and then need to pass this wherever needed. With Spring boot I can load the full file and can get the access of the values though keys. But how I can load the whole configuration file into Properties object or pass the spring loaded property (not a single value rather all the values) wherever required?

My current code:

Properties myProps= new Properties();
myProps.load(resourceAsStream);

CodePudding user response:

If you're looking for specific ways of loading them using Spring-boot I'd suggest looking into:

  • Binding properties to an object by using the @Configuration, @ConfigurationProperties and @PropertySource annotations if you want to enforce and implicitly manage type-safety at all times
  • The Environment interface you can @AutoWire to your classes, if you don't need to enforce type-safety at all times (you can still do it, but you're not forced to). @PropertySource can be used in this case as well to load properties outside the default default-loaded application.properties, although they'll be loaded only when the application context refreshes (e.g. they won't be available while the application is booting up)
  • The PropertiesLoaderUtils class, as suggested in the comments, if you want to selectively load a configuration file at runtime for example

I usually recommend the first. The result is the same as using an @AutoWired Environment, with the advantages of implicit type-safety and improved readability. You can then get the properties and write them inside your java.util.properties if you need them to be there.

However, there is more than one way to do that, both using Spring-Boot or not. Loading properties like that is also perfectly fine, although arguably not the best practice since you're using Spring-boot.

  • Related