当然,这是可能的。您必须像这样注册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
SomeDataSourceImpl
是javax.sql.DataSource的一些具体实现。请告知您是否不使用特定DataSource
的 s(例如用于连接池的ComboPooledDataSource)并且不知道如何获取它 - 我将发布如何绕过它。
some-data-source-alias
- 只是属性映射中实例的String
别名(键) 。好的做法是提供带有包名的别名,例如.DataSource
ServletContext
com.mycompany.mywebapp.dataSource
希望这可以帮助...