有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaTomcat8上下文。xml在数据源中使用环境变量

我有一个使用数据源的Tomcat8项目(见下文)

<Resource auth="Container" 
          name="jdbc/JtmDS"  
          driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
          type="javax.sql.DataSource" 
          username="xfer"
          password="xfer10" 
          url="jdbc:derby:/home/PUID/tm/control/JtmDB"                    
          initialSize="25"
          maxTotal="100" 
          maxIdle="30" 
          maxWaitMillis="10000"                                      
          removeAbandonedOnBorrow="true"
          removeAbandonedTimeout="20" />

这非常有效

但是,url是硬编码路径/home/PUID/tm/control/JtmDB

当它投入生产时,路径的PUID部分将在多个系统中有所不同。 我有一个环境变量集export PUID=abcd 应用程序的其余部分可以在适当的时候使用System.getenv( )${env:PUID}之类的东西

这些都很好用

我的问题很简单: 如何在上下文中生成PUID值。xml是一个可以从环境变量中读取的变量吗


共 (1) 个答案

  1. # 1 楼答案

    我终于发现了我真正需要在这里做什么。。。。最后很简单

    我在运行时向Tomcat传递了一个java参数,如下所示

    我向setenv.sh添加了以下位

    export PUID=abcd
    
    JAVA_OPTS=-Dpuid=${PUID} 
    

    然后编辑了我的背景。如图所示

    <Resource auth="Container" 
              name="jdbc/JtmDS"  
              driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
              type="javax.sql.DataSource" 
              username="xfer"
              password="xfer10" 
              url="jdbc:derby:/home/${puid}/tm/control/JtmDB"                    
              initialSize="25"
              maxTotal="100" 
              maxIdle="30" 
              maxWaitMillis="10000"                                      
              removeAbandonedOnBorrow="true"
              removeAbandonedTimeout="20" />
    

    现在我的Tomcat安装将阅读这篇文章,并且能够为每个不同的PUID使用不同的路径


    背景:这是因为Tomcat将在其配置文件中自动执行变量替换:

    Tomcat configuration files are formatted as schemaless XML; elements and attributes are case-sensitive.

    Apache Ant-style variable substitution is supported; a system property with the name propname may be used in a configuration file using the syntax ${propname}. All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.

    Apache Tomcat 9 Configuration Reference - Overview

    该部分:

    JAVA_OPTS=-Dpuid=${PUID}
    

    上面的描述是必要的,因为Tomcat只读取Java system properties(由JVM提供),而不读取环境变量(由JVM运行的OS/运行时库提供)。 参数-D从同名的环境变量设置Java系统属性