基於Spring的Java應用會通過ApplicationContext
接口提供應用程序配置。我們常常需要在代碼中獲取當前的ApplicationContext
。如在集成測試時,需要通過ApplicationContext
獲取各種Bean。這時可以使用FileSystemXmlApplicationContext
通過提供配置文件的路徑,來得到應用程序上下文:
String[] paths = { "applicationContext.xml", ...};
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths);
SomeBean bean = (SomeBean) ctx.getBean("someBean");
在實際生產中,往往會根據不同的客戶情況部署不同的配置,所以配置文件不能寫死在代碼中。這時應該通過HttpServlet
來獲取應用程序上下文。比如,我們可以定義一個ApplicationContextWrapper
類,提供全局的ApplicationContext
:
public class ApplicationContextWrapper {
private static ApplicationContext applicationContext;
public synchronized static void setApplicationContext(ApplicationContext context) {
applicationContext = context;
}
public static ApplicationContext current() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}
同時,要自定義一個HttpServlet
,在init
方法中通過傳入的ServletConfig
和WebApplicationContextUtils
來設置ApplicationContextWrapper
:
public class ApplicationContextLoaderServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
ApplicationContextWrapper.setApplicationContext(
WebApplicationContextUtils.getWebApplicationContext(
config.getServletContext()));
}
}
當然,不要忘了在web.xml中配置這個servlet:
<servlet>
<servlet-name>ApplicationContextLoaderServlet</servlet-name>
<servlet-class>
net.kirin.sample.ApplicationContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
這樣就可以在代碼中使用ApplicationContext
了:
DataSource dataSource = (DataSource) ApplicationContextWrapper.getBean("dataSource");