spring在web项目中ApplicationContext容器的实例化

spring IoC设计的核心是Bean容器,BeanFactory采用了java的工厂模式,通过从XML配置文件中读取JavaBean的定义,来实现JavaBean的创建、配置和管理。所以BeanFactory可以成为IoC容器。而ApplicationContext扩展了BeanFactory容器并添加了对国际化、资源访问、事件传播等方面有良好的支持可以应用在java App和java Web中。在java项目中通过ClassPathXMLApplicationContext类手工实例化ApplicationContext容器十分合适。但是对于web项目就不行了,web项目的启动是由相应的web服务器负责的。因此,在web项目中ApplicationContext容器的实例化工作最好由web服务器来完成。

spring提供两种方式

(1)基于ContextLoaderListener实现。

web.xml中添加:

<!--指定spring配置文件的位置,多个配置文件以逗号分隔-->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<!--指定以listener方式启动spring容器-->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

(2)基于ContextLoaderServlet实现。

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的含义就是其中的参数大于等于零的时候表示容器在启动的时候就加载这个servlet-->

<load-on-startup>1</load-on-startup>

</servlet>

猜你喜欢

转载自www.cnblogs.com/olzoooo/p/10473065.html