我在context.xml中有一个DataSource配置。是否可以不在该文件中对数据库参数进行硬编码?例如,使用外部属性文件,并从中加载参数?
像这样的东西:
context.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
发布于 2012-07-13 19:13:38
当然,这是可能的。您必须将ServletContextListener注册到您的web.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
SomeDataSourceImpl
是javax.sql.DataSource的一些具体实现。如果您不使用特定的DataSource
(如用于连接池的ComboPooledDataSource ),并且不知道如何获得它,请告知-我将发布如何绕过它。
some-data-source-alias
-只是DataSource
属性映射中ServletContext
实例的ServletContext
别名(键)。较好的做法是在别名前面加上包名称,如com.mycompany.mywebapp.dataSource
。
希望这能帮到你。
发布于 2012-07-16 09:12:50
如果这是Tomcat7,您可以在context.xml
中编写自己的org.apache.tomcat.util.IntrospectionUtils.PropertySource
实现读取变量,如"${...}“。您需要设置系统属性org.apache.tomcat.util.digester.PROPERTY_SOURCE
以指向您的PropertySource
实现。
https://stackoverflow.com/questions/11468881
复制相似问题