18

我在 context.xml 中有一个 DataSource 配置。是否可以不在该文件中硬编码数据库参数?例如,使用外部属性文件,并从中加载参数?

像这样的东西:

上下文.xml:

  <Resource
  name="jdbc/myDS" auth="Container"
  type="javax.sql.DataSource"
  driverClassName="oracle.jdbc.OracleDriver"
  url="${db.url}"
  username="${db.user}"
  password="${db.pwd}"
  maxActive="2"
  maxIdle="2"
  maxWait="-1"/>

db.properties:

db.url=jdbc:oracle:thin:@server:1521:sid
db.user=test
db.pwd=test
4

4 回答 4

13

如此处所述,您可以通过以下方式执行此操作。

1.下载tomcat库获取接口定义,例如定义maven依赖:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-coyote</artifactId>
        <version>7.0.47</version>
    </dependency>

2.下一步是通过以下方式创建一个com.mycompany.MyPropertyDecoder:

import org.apache.tomcat.util.IntrospectionUtils;
public class MyPropertyDecoder implements IntrospectionUtils.PropertySource  {
    @Override
    public String getProperty(String arg0) {
        //TODO read properties here
        return null;
    }
}

3.将 MyPropertyDecoder.class 放入tomcat7/lib文件夹
4.定义 org.apache.tomcat.util.digester。tomcat7/conf/catalina.properties中的PROPERTY_SOURCE 属性如下:

org.apache.tomcat.util.digester.PROPERTY_SOURCE=com.mycompany.MyPropertyDecoder

5.用属性变量更新你的 context.xml

<Resource name="jdbc/TestDB"
           auth="Container"
           type="javax.sql.DataSource"
           username="root"
           password="${db.password}"
           driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/mysql?autoReconnect=true"
           ...  

6.将application.properties文件放在项目/容器中的某个位置 7.
确保MyPropertyDecoder正确读取application.properties
8.享受!

PS tc Server也有类似的方法。

于 2013-11-14T08:45:58.433 回答
5

使用上下文部署描述符很容易,如下所示:

<Context docBase="${basedir}/src/main/webapp"
         reloadable="true">
    <!-- http://tomcat.apache.org/tomcat-7.0-doc/config/context.html -->
    <Resources className="org.apache.naming.resources.VirtualDirContext"
               extraResourcePaths="/WEB-INF/classes=${basedir}/target/classes,/WEB-INF/lib=${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <Loader className="org.apache.catalina.loader.VirtualWebappLoader"
            virtualClasspath="${basedir}/target/classes;${basedir}/target/${project.build.finalName}/WEB-INF/lib"/>
    <JarScanner scanAllDirectories="true"/>

    <Parameter name="min" value="dev"/>
    <Environment name="app.devel.ldap" value="USER" type="java.lang.String" override="true"/>
    <Environment name="app.devel.permitAll" value="true" type="java.lang.String" override="true"/>
</Context>

有几个地方可以放置这个配置,我认为最好的选择是$CATALINA_BASE/conf/[enginename]/[hostname]/$APP.xml

在上面的 XMLContext中可以保存自定义Loader org.apache.catalina.loader.VirtualWebappLoader(在现代 Tomcat 7 中可用,您可以为每个应用程序添加自己单独的类路径到您的.properties文件),Parameter(通过访问FilterConfig.getServletContext().getInitParameter(name))和Environment(通过访问new InitialContext().lookup("java:comp/env").lookup("name")

见讨论:

更新 Tomcat 8 更改 <Resources><Loader>元素的语法,对应的部分现在看起来像:

<Resources>
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/classes" base="${basedir}/target/classes" />
    <PostResources className="org.apache.catalina.webresources.DirResourceSet"
                   webAppMount="/WEB-INF/lib" base="${basedir}/target/${project.build.finalName}/WEB-INF/lib" />
</Resources>
于 2014-10-01T17:31:05.463 回答
2

当然,这是可能的。您必须像这样注册ServletContextListenerweb.xml

<!-- at the beginning of web.xml -->

<listener>
    <listener-class>com.mycompany.servlets.ApplicationListener</listener-class>
</listener>

来源com.mycompany.servlets.ApplicationListener

package com.mycompany.servlets;

public class ApplicationListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // this method is invoked once when web-application is deployed (started)

        // reading properties file
        FileInputStream fis = null;
        Properties properties = new Properties();
        try {
            fis = new FileInputStream("path/to/db.properties")    
            properties.load(fis);
        } catch(IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            try {
                if(fis != null) {
                    fis.close();
                }
            } catch(IOException e) {
                throw new RuntimeException(e);
            }
        }

        // creating data source instance
        SomeDataSourceImpl dataSource = new SomeDataSourceImpl();
        dataSource.setJdbcUrl(properties.getProperty("db.url"));
        dataSource.setUser(properties.getProperty("db.user"));
        dataSource.setPassword(properties.getProperty("db.pwd"));

        // storing reference to dataSource in ServletContext attributes map
        // there is only one instance of ServletContext per web-application, which can be accessed from almost anywhere in web application(servlets, filters, listeners etc)
        final ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("some-data-source-alias", dataSource);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // this method is invoked once when web-application is undeployed (stopped) - here one can (should) implement resource cleanup etc
    }

}

然后,在 Web 应用程序代码中的某个地方访问dataSource

ServletContext servletContext = ...; // as mentioned above, it should be accessible from almost anywhere
DataSource dataSource = (DataSource) servletContext.getAttribute("some-data-source-alias");
// use dataSource

SomeDataSourceImpljavax.sql.DataSource的一些具体实现。请告知您是否不使用特定DataSource的 s(例如用于连接池的ComboPooledDataSource)并且不知道如何获取它 - 我将发布如何绕过它。

some-data-source-alias- 只是属性映射中实例的String别名(键) 。好的做法是提供带有包名的别名,例如.DataSourceServletContextcom.mycompany.mywebapp.dataSource

希望这可以帮助...

于 2012-07-13T11:13:37.837 回答
0

如果这是 Tomcat 7,您可以编写自己的org.apache.tomcat.util.IntrospectionUtils.PropertySource实现读取变量,如 "${...}" in context.xml. 您需要将系统属性设置org.apache.tomcat.util.digester.PROPERTY_SOURCE为指向您的PropertySource实现。

于 2012-07-16T01:12:49.997 回答