Strategies for java webapp configuration

蹲街弑〆低调 提交于 2019-12-04 10:22:06

Simple things like a String can be declared as environment entries in the web.xml and obtained via JNDI. Below, an example with an env-entry named "imagePath".

<env-entry> 
    <env-entry-name>imagePath</env-entry-name> 
    <env-entry-value>/somepath_on_production_server/images</env-entry-value> 
    <env-entry-type>java.lang.String</env-entry-type> 
</env-entry>

To access the properties from your Java code, do a JNDI lookup:

// Get a handle to the JNDI environment naming context
Context env = (Context)new InitialContext().lookup("java:comp/env");

// Get a single value
String imagePath = (String)env.lookup("imagePath");

This is typically done in an old fashioned ServiceLocator where you would cache the value for a given key.

Another option would be to use a properties files.


And the maven way to deal with multiple environments typically involves profiles and filtering (either of a properties file or even the web.xml).

Resources

Have defaults in your WAR file corresponding to the production setting, but allow them to be overriden externally e.g. through system properties or JNDI.

String uploadLocation = System.getProperty("upload.location", "c:/dev");

(untested)

Using a properties file isn't too difficult and is a little more readable the web.xml

InputStream ldapConfig = getClass().getResourceAsStream(
          "/ldap-jndi.properties");
      Properties env = new Properties();
      try {
        env.load(ldapConfig);
      } finally {
        if (ldapConfig != null) {
          ldapConfig.close();
        }
      }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!