有没有办法从Java Bean访问web.xml属性?
Servlet API中是否可以从根本不与Web容器关联的Bean或者Factory类中访问web.xml中指定的属性(如初始化参数)?
例如,我正在编写一个Factory类,并且我想在Factory中包括一些逻辑,以检查文件和配置位置的层次结构,以查看是否有可用的以确定实例化哪个实现类,
- 类路径中的属性文件,
- 一个web.xml参数,
- 系统属性,或者
- 如果没有其他可用的默认逻辑。
我希望能够做到这一点,而无需注入对ServletConfig的任何引用或者任何类似于我的Factory的代码,该代码应能够在Servlet容器之外正常运行。
这听起来似乎有点不常见,但是我希望我正在研究的这个组件能够与我们的一个webapp打包在一起,并且还具有足够的通用性,可以与我们的某些命令行工具打包在一起而无需需要仅用于我的组件的新属性文件,因此我希望搭载在其他配置文件(例如web.xml)的顶部。
如果我没记错的话,.NET有类似Request.GetCurrentRequest()
之类的东西来获取对当前正在执行的Request
的引用,但是由于这是一个Java应用程序,我正在寻找类似的东西来获取对它的访问权限。 ServletConfig
解决方案
回答
我们是否考虑过使用Spring框架?这样,bean就不会再有多余的东西了,而spring会为我们处理配置设置。
回答
我认为我们将必须添加一个关联的引导程序类,该类将引用ServletConfig(或者ServletContext)并将这些值转录为Factory类。至少通过这种方式,我们可以将其单独打包。
@toolkit:非常好,最谦卑的这是我一段时间以来一直在尝试的事情
回答
我们可以这样做的一种方法是:
public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration<?> keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } }
然后在web.xml中添加以下内容
<listener> <listener-class>com.acme.FactoryInitialisingServletContextListener<listener-class> </listener>
如果应用程序在Web容器中运行,则在创建上下文后,容器将调用侦听器。在这种情况下,_servletContextProperties将替换为web.xml中指定的任何上下文参数。
如果应用程序在Web容器外部运行,则_servletContextProperties将为空。