通过xml配置文件

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

第一种方式:FileSystemXmlApplicationContext

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

获得ApplicationContext_XML

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml")

获得ApplicationContext_XML

ac.getBean("beanName");

<!--more-->

第二种方式:WebApplicationContextUtil

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

获得ApplicationContext_XML

ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);

获得ApplicationContext_XML

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);

获得ApplicationContext_XML

下面几种方式没有用过,

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

 

方法三:继承自抽象类ApplicationObjectSupport

可以方便的获取到

会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

 

方法四:继承自抽象类WebApplicationObjectSupport

说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

方法五:实现接口ApplicationContextAware 说明:实现该接口的setApplicationContext(ApplicationContext context)方法,

并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。

抽象类ApplicationObjectSupport提供getApplicationContext()方法