简体   繁体   中英

ResourceBundle file outside jar

I have a spring boot application with /resources/application.properties , when deployed there is a application.properties next to the jar (and the one inside it).

Somewhere in the code I use ResourceBundle.getBundle("application").getString("x") but that always return the value defined in the properties inside the jar.

My objective is to get the value from the external file if it exists, if not then I need to get the value from inside the jar. Just like the default springs behavior but I'm not able to achieve this.

edit:

You can either use the solution in the correct answer below or you can rely on springs Environment by autowiring it and using getProperty()

ResourceBundle.getBundle(String baseName) relies on the classloader and not directly the file system to find the resource.
This is equivalent to invoke the overloaded one:

getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader()), 

So your result is expected.
What you look for is PropertyResourceBundle .
To create an instance of you need either a Reader or an InputStream .

You could load both external and internal files.

ResourceBundle internalProps = ResourceBundle.getBundle("application");
ResourceBundle externalProps = new  PropertyResourceBundle(Files.newInputStream(Paths.get("application.properties"));

You could so use the external ResourceBundle in first intention and the second one as fallback.

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