![](/img/trans.png)
[英]spring web application context is not loaded from jar file in WEB-INF/lib when running tomcat in eclipse
[英]how to load a 'mini' spring context from WEB-INF in order to initialize the real application context
我有一個遺留的Spring 3 Web應用程序,它使用配置數據庫來加載配置值,如URL,超時等。
目前,config-db中的值以編程方式使用。
目前有一個應用程序上下文,其中配置數據庫訪問器代碼沿所有其他組件初始化(Spring Repository)。
由於此單個上下文,config-database中的配置值不能用於“@Value”注釋。 當我可以訪問值時,初始化上下文,創建bean。
目標是允許通過bean中的'@Value'注釋使用基於config-db的值。
所以我的想法是將config-db訪問器bean(數據源,實體管理器等)分離為“迷你”上下文,並且:
幾乎所有東西都取得了成功,但我只能從類路徑初始化這個'迷你上下文',而不是從WEB-INF初始化(WEB-INF不在類路徑上,只有WEB-INF /類)。 我當前的初始化如下所示:
注冊Spring調度程序servlet的上下文偵聽器:
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextInitializerClasses</param-name>
<param-value>xxx.xxx.ContextInitializer</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
然后在ContextInitializer中:
public void initialize(ConfigurableApplicationContext applicationContext) {
ClassPathXmlApplicationContext miniContext =
new ClassPathXmlApplicationContext("jpa-context-for-config-db.xml");
ParameterDao parameterDao = miniContext.getBean(ParameterDao.class);
Properties propertiesFromConfigDb = getPropertiesFromConfigDb(parameterDao);
applicationContext.getEnvironment().getPropertySources().addFirst(
new PropertiesPropertySource("parameterDaoBasedProperties", propertiesFromConfigDb));
miniContext.close();
}
這是有效的,但是
我必須將迷你上下文xml放入/ WEB-INF / classes,而不是其他上下文文件所在的位置(其他上下文文件位於/ WEB-INF中)
我不能在'location =“/ WEB-INF / ....”'的迷你上下文中使用property-placeholders或util:properties。
我嘗試使用GenericXmlApplicationContext並使用它的setResourceLoader但尚未成功。
那么有沒有辦法以編程方式從WEB-INF而不是從類路徑加載spring context.xml?
在spring Web應用程序中,可以通過org.springframework.web.context.support.ServletContextResourceLoader訪問WEB-INF的內容。 該類可以從WEB-INF加載資源。
所以initialize方法應如下所示:
public void initialize(ConfigurableApplicationContext applicationContext) {
ServletContext servletContext = ContextLoaderListener.getCurrentWebApplicationContext().getServletContext();
GenericXmlApplicationContext miniContext = new GenericXmlApplicationContext();
miniContext.setResourceLoader(new ServletContextResourceLoader(servletContext));
miniContext.load("/WEB-INF/jpa-context-for-config-db.xml");
miniContext.refresh();
ParameterDao parameterDao = miniContext.getBean(ParameterDao.class);
Properties propertiesFromConfigDb = getPropertiesFromConfigDb(parameterDao);
applicationContext.getEnvironment().getPropertySources().addFirst(
new PropertiesPropertySource("parameterDaoBasedProperties", propertiesFromConfigDb));
miniContext.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.