ITeye博客

取WebApplicationContext方法集

cjh326419411 · 2012-11-14 16:10 · Spring · JSP/Servlet · 编程语言 · Markdown

通过xml配置文件

  bean配置在xml里面,spring提供多种方式读取配置文件得到ApplicationContext.

第一种方式:FileSystemXmlApplicationContext

通过程序在初始化的时候,导入Bean配置文件,然后得到Bean实例:


ApplicationContext ac = new FileSystemXmlApplication Context("applicationContext.xml")
ac.getBean("beanName");

第二种方式:WebApplicationContextUtil

在B/S系统中,通常在web.xml初始化bean的配置文件,然后由WebAppliCationContextUti l得到ApplicationContext.例如:


ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);

其中 servletContext sc 可以具体 换成 servlet.getServletContext()或者 this.getServletContext() 或者 request.getSession().getServletContext();

另外,由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:


WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

getRequiredWebApplicatio nContext和 getWebApplicationContext 的区别是,获取失败时候,getRequiredWebApplicatio nContext抛出异常,getWebApplicationContext 抛出null

方法三:继承自抽象类ApplicationObjectSupport

说明:可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的 setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport 说明:类似上面方法,调用getWebApplicationContext ()获取WebApplicationContext

方法五:实现接口ApplicationContextAware 说明:实现该接口的setApplicationContext(ApplicationContext context)方法, 并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。