![](/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.