![](/img/trans.png)
[英]No bean named 'springSecurityFilterChain' is defined in combination of Web.xml and Java Config
[英]Is there a way to access web.xml properties from a Java Bean?
Servlet API中是否有任何方法可以从与Web容器完全无关的Bean或Factory类中访问web.xml中指定的属性(例如初始化参数)?
例如,我正在编写一个Factory类,我想在Factory中包含一些逻辑来检查文件和配置位置的层次结构,以查看哪些可用于确定实例化哪个实现类 - 例如,
我希望能够在不注入ServletConfig
任何引用或类似于我的Factory的任何内容的情况下执行此操作 - 代码应该能够在Servlet容器之外运行。
这可能听起来有点不常见,但是我想要这个组件,我正在努力与我们的一个webapp一起打包,并且还具有足够的通用性,可以与我们的一些命令行工具一起打包需要一个新的属性文件只为我的组件 - 所以我希望搭载其他配置文件,如web.xml。
如果我没记错的话,.NET有类似Request.GetCurrentRequest()
来获取对当前正在执行的Request
的引用 - 但由于这是一个Java应用程序,我正在寻找可以用来获取ServletConfig
访问权限的东西。
你可以这样做的一种方法是:
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中指定的任何context-params。
如果您的应用程序在Web容器外部运行,则_servletContextProperties将为空。
您是否考虑过使用Spring框架? 这样,你的bean不会得到任何额外的瑕疵,spring会为你处理配置设置。
我认为您必须添加一个关联的引导类,它引用ServletConfig(或ServletContext)并将这些值转录到Factory类。 至少这种方式你可以单独打包它。
@toolkit:非常好,最谦卑 - 这是我一直试图做的事情
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.