Spring IoC容器的设计主要基于BeanFactory和ApplicationContext两个接口。
1、Bean工厂BeanFactory【这种加载方式在实际开发中并不多见,了解即可】,语法如下:
BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("X:/bean.xml"));
2、Bean工厂ApplicationContext,是BeanFactory的子接口之一【相当于BeanFactory是Spring IoC容器所定义的最底层接口,而ApplicationContext是其高级接口之一,所以该方式是常用的】有三个常用的实现类:
- ApplicationContext ctx = new ClassPathXmlApplicationContext(String configLocation);
- ApplicationContext ctx = new FileSystemXmlApplicationContext(String configLocation);
- ServletContextCleaner servletContextCleaner = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContextCleaner);
3、Web项目的启动是由相应的Web服务器负责的,因此在Web项目中,ApplicationContext容器的实例化工作交给了Web服务器来完成,为此Spring提供了以下两种方式:
3-1:基于ContextLoaderListener实现:这种方式只适用于Servlete2.4及以上规范的Servlet,需要在web.xml中添加如下代码:
<!-- 指定Spring配置文件的位置,多个配置文件以逗号分隔 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 指定以ContextLoaderListener方式启动Spring容器-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
3-2:基于ContextLoaderServlet实现:这种方式只适用于Servlete2.4及以上规范的Servlet,需要在web.xml中添加如下代码:
<!-- 指定Spring配置文件的位置,多个配置文件以逗号隔开 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--指定以Servlet方式启动Spring容器-->
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>