1,在Java中,用spring的框架,我们都会通过ApplicationContext接口提供应用程序配置。我们常常需要在代码中获取当前的ApplicationContext。有时会需要通过ApplicationContext获取各种Bean。这时可以使用FileSystemXmlApplicationContext通过提供配置文件的路径,来得到应用程序上下文:
String[] paths = { “applicationContext.xml”, …};
ApplicationContext ctx = new FileSystemXmlApplicationContext(paths);
SomeBean bean = (SomeBean) ctx.getBean(“someBean”)
2,在我们的实际开发中,便于开发人员根据需求的变动,而无需进入源码进行修改。
这时应该通过HttpServlet来获取应用程序上下文。因此,可以定义一个ApplicationContextUtils类,提供全局的ApplicationContext:
public class ApplicationContextUtils {
private static Log logger = LogFactory.getLog(ApplicationUtils.class);
public static ApplicationContext applicationContext;
//在此处用同步锁。
public static void setApplicationContext(ApplicationContext applicationContext) {
Class arg0 = ApplicationUtil.class;
synchronized (ApplicationUtil.class) {
logger.info(“setApplicationContext, notifyAll”);
ApplicationUtil.applicationContext = applicationContext;
ApplicationUtil.class.notifyAll();
}
}
public static ApplicationContext getApplicationContext() {
Class arg = ApplicationUtil.class;
synchronized (ApplicationUtil.class) {
while (applicationContext == null) {
try {
logger.info("getApplicationContext, wait...");
ApplicationUtil.class.wait(300000L);
if (applicationContext == null) {
logger.warn(
"Have been waiting for ApplicationContext to be set for 5 minute",
new Exception());
}
} catch (InterruptedException arg2) {
logger.warn("getApplicationContext, wait interrupted");
}
}
return applicationContext;
}
}
到此处了 ,你需要写一个自定义的httpservlet ,此时我们写一个ApplicationContextServlet,初始化时传入
init方法中通过传入的ServletConfig和WebApplicationContextUtils
public class ApplicationContextServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
ApplicationContextUtils.setApplicationContext(
WebApplicationContextUtils.getWebApplicationContext(
config.getServletContext()));
}
}
此时我们便完成了获取ApplicationContext的步骤
紧接着,
我们需要在我们的工程中,引入我们刚写的servlet
< servlet>
< servlet-name>名称< /servlet>
< servlet-calss>类路径< /servlet>
< load-on-startup>1< /load-on-startup>
< /servlet>
因为我们的servlet 不是共外部使用,所以无需配置请求处理的虚拟路径