简体   繁体   中英

Where to store web application's configuration variables?

Why would you not store web application's configuration variables simply in a class file?

I need to store variables like as how many product items to show in one page at a time. Where should I store them as such that my Java classes can use them? What is the standard for this?

Why would you not store web application's configuration variables simply in a class file?

That would require rebuilding, redeploying and restarting the whole beast whenever you make minor edits. It's maybe not painful if you're just locally hobbying. But in real world (when done rightly) you would need to get it through the whole chain of continuous build, automated testing, QA, etc. This makes no sense for a silly change in a configuration setting.

Your webapp must be designed that way that configuration can be changed externally and preferably also that it is able to reload configuration on demand (eg a button on an admin page) or even automatically (eg by @Schedule @Singleton ). This way the serveradmin has just to edit a simple and self-documenting textbased file instead of waiting hours or even days to get it into production.

You save it within your project...

Reading and Writing a Properties File

// Read properties file.
Properties properties = new Properties();
try {
    properties.load(new FileInputStream("filename.properties"));

} catch (IOException e) {
}

//read an item
String prop = properties.getProperty("a");

// Write properties file.
try {
    properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}

Here is an example of the contents of a properties file:

# a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
    continuation line
d.e.f = another string

taken from: http://www.exampledepot.com/egs/java.util/Props.html

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