简体   繁体   中英

How do I use ResourceBundle to avoid hardcoded config paths in Java apps?

I'd like to eliminate dependencies on hardcoded paths for configuration data in my Java apps, I understand that using ResourceBundle will help me use the classloader to find resources.

Can someone tell me how I would replace a hardcoded path to a resource (say a .properties configuration data file required by a class) with appropriate use of ResourceBundle? Simple clear example if possible, thanks all.

You will want to examine Resource.getBundle(String) . You pass it the fully qualified name of a resource on the classpath to load as a properties file.

Prior to Java 6, ResourceBundle typically allowed:

Java 6 comes with the ResourceBundle.Control class which opens the door to other sources of ResourceBundles, for example:

  • XML files (see example 2 in Javadoc)
  • Database rows

Hope this helps.

You don't need a ResourceBundle. A simple Properties object can do the job. Just use the classloader to get an inputstream for you properties file and use it to load de values. If you need to handle more sophisticated user configurations, use the preferences api .

Kind Regards

The trick behind Resource.getBundle(..) is the use of the classloader. You can load everything thats in your classpath by accessing it via this.getClass().getClassLoader(). Resource.getBundle(..) is a practical helper to use it in the resource/locatization topic.

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