This link has been bookmarked by 1 people . It was first bookmarked on 15 Aug 2007, by Colin Wong.
.直接召唤系--Singleton的Application Context
最简单的,就像在UnitTest里那样,直接构造Application Context:
ApplicationContext ctx = new ClasspathXmlApplicationContext("ApplicationContext.xml");
在Web环境里,会使用ContextLoader构造ApplicationContext后,压进Servlet Context。
由ContextLoaderListener或ContextLoaderServlet,在Web应用启动时完成。
然后在Jsp/Servelet中,可以通过Servlet Context取得ApplicationContext: ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
然后让loactor去找它,但代码有点长: BeanFactoryReference bfr = DefaultLocatorFactory.getInstance().useBeanFactory("default-context");
BeanFactory factory = bfr.getFactory();
MyService myService = factory.getBean("myService");
bfr.release();
// now use myService
上面的代码实在是太灵活,太麻烦了。
还不如自己实现一个简单的Singleton,扩展ContextLoaderListener类,在Web系统启动时压入Singleton。
新的ContextLoaderListener类重载如下,ContextUtil中包含一个静态的ApplicationContext变量:
public void contextInitialized(ServletContextEvent event)
{
super.contextInitialized(event);
ServletContext context = event.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
ContextUtil.setContext(ctx);
}
用家可直接取用:
ApplicationContext context = ContextUtil.getContext();
Would you like to comment?
Join Diigo for a free account, or sign in if you are already a member.