System.getProperty(“catalina.base”) There can be scenario where client may use any other server

前端 未结 3 1066
情歌与酒
情歌与酒 2021-01-11 11:12

I am reading a properties file from the Tomcat\\conf\\somename.properties directory using

String demo = System.getProperty(\"catalina.base\") +         


        
3条回答
  •  天涯浪人
    2021-01-11 11:22

    There are basically two ways.

    1. Just add its path to the runtime classpath so that you can get it from the classpath the usual way. In case of Tomcat, you can add external folders to the runtime classpath by specifying it in the shared.loader property of /conf/catalina.properties. E.g.

      shared.loader = ${catalina.home}/conf

      Or better, don't be server-specific

      shared.loader = /path/to/folder

      Other servers also supports adding external folders to the classpath, consult their documentation.

      This way you'll be able to get an InputStream of it from the classpath as follows:

      InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/config.properties");
      Properties properties = new Properties();
      properties.load(input);
      // ...
      

    2. Add another server-independent system property yourself, you can set as a VM argument.

      -Dconfig.location=/path/to/folder

      In case of Tomcat, you can set it as JAVA_OPTS environment variable, or edit the catalina.bat startup file or edit the Windows Service settings (when it's installed as Windows Service), etc. Other servers supports similar constructs as well.

      This way you can obtain it as follows

      File file = new File(System.getProperty("config.location"), "config.properties");
      InputStream input = new FileInputStream(file);
      Properties properties = new Properties();
      properties.load(input);
      // ...
      

    Either way you choose, when distributing your application, you should document it properly so that the serveradmin can configure it accordingly.


    Unrelated to the problem, the ResourceBundle is not the right way to read configuration properties files. It's intented for localized content for internationalization.

提交回复
热议问题