java - System.getProperty ("catalina.base") 可能存在客户端可以使用任何其他服务器的情况

标签 java

我正在使用

Tomcat\conf\somename.properties 目录中读取属性文件
String demo = System.getProperty("catalina.base") +
                  File.separator + "conf" + File.separator + "somename.properties";

这在 Tomcat 上工作得很好。但是,在某些情况下,客户端可能会使用任何其他服务器,例如 Glassfish 或 Websphere,在这种情况下,我将无法获取 System.getProperty("catalina.base")

我该如何正确解决呢?我可以使用 ResourceBundle 来做到这一点,但为此我必须将我的属性文件保留在我的构建中,这是我不想要的。我只想从我的构建外部读取我的属性文件。

最佳答案

基本上有两种方法。

  1. 只需将它的路径添加到运行时类路径中,这样您就可以按照通常的方式从类路径中获取它。对于 Tomcat,您可以通过在 /conf/catalina.propertiesshared.loader 属性中指定外部文件夹来将其添加到运行时类路径。例如

    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. 自己添加另一个与服务器无关的系统属性,您可以将其设置为 VM 参数。

    -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);
    // ...
    

无论您选择哪种方式,在分发您的应用程序时,您都应该正确记录,以便服务器管理员可以相应地配置它。


与此问题无关ResourceBundle 不是读取配置属性文件的正确方法。它旨在用于国际化的本地化内容。

关于java - System.getProperty ("catalina.base") 可能存在客户端可以使用任何其他服务器的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6113238/

相关文章:

java - 启动 MQ Listener 时出现 MQJCA1025 错误

java - Java/MySQL 中的 if/else 语句

java - 如何在不使用 Java 8 Stream 的情况下查找 Java 中两个 ArrayList<Integer> 之间的差异?

java - 如何在不使用注释的情况下使用 JAXB 将 java 对象转换为 xml?

java - InputStreamReader 并从 .txt 文件中读取随机行

java - 使用java spring和GMail发送电子邮件

java - 如何在Android Studio中正确导入Android项目?

java - 如何编写正则表达式来匹配 yaml 文件中的键?

Java Quartz cron 表达式

java - .NET using-Statement 和 Java try-with-resources 之间的区别