在web项目中如何启动spring容器?

来源:互联网 发布:益思留学 知乎 编辑:程序博客网 时间:2024/06/07 17:13

1.在web.xml配置spring配置文件的信息

 <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:config/applicationContext-beans.xml</param-value>  </context-param>


2.在web.xml配置spring监听

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

<listener>     <listener-class>com.test.ApplicationContextListener</listener-class> </listener> 

以上两种方式,一般采用第一种方式,第二种方式中ApplicationContextListener是org.springframework.web.context.ContextLoaderListener的子类。ContextLoaderListener实现ServletContextListener,读取contextConfigLocation中定义的xml文件,如果不设置contextConfigLocation的初始参数则默认会读取WEB-INF路径下的 applicationContext.xml文件。ContextLoaderListener读取这些XML文件并产生 WebApplicationContext对象,然后将这个对象放置在ServletContext的属性里,这样我们只要可以得到Servlet就可以得到WebApplicationContext对象,并利用这个对象访问spring容器管理的bean。

原创粉丝点击