Spring笔记

本文介绍了如何在Tomcat等Web服务器中加载Spring配置文件,并详细解释了ContextLoaderListener和ContextLoaderServlet两种机制的使用方法。此外,还提供了在web.xml中指定配置文件位置的具体配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      最近正在学习spring,顺便做一下小结。

     1.在web服务器(比如tomcat)中加载spring配置文件。

     在spring中,与BeanFactory通常以编程的方式被创建不同,ApplicationContext能以声明的方式创建,一般采用ContextLoader,ContextLoader机制有两种实现方式,即:ContextLoaderListener和ContextLoaderServlet.在web.xml中的配置如下:

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

 

<servlet>
   <servlet-name>context</servlet-name>
   <servlet-class>
       org.springframework.web.context.ContextLoaderservlet
   </servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

     请注意:在一个应用中,我们只能选择其中之一进行配置,推荐使用 ContextLoaderListener,我们可以通过继承ContextLoaderListener或者ContextLoaderservlet类,重写init方法或者destroy方法,就可以提供自己的启动和销毁时的任务,比如在启动时,通过连接查询数据库,获取并存储一些必要的常量等等。

     2.spring配置文件的位置

      这个是很多初学者比较头疼的问题,在开发spring应用时,经常发现找不到
applicationContext.xml文件,为了让web容器在启动时,能够找到spring配置文件,我们可以在web.xml中做如下配置:

 

<!--spring配置文件在src文件夹下的某个package下时的配置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath*:com.cn.applicationContext.xml
   </param-value>
</context-param>

<!--spring配置文件在WebRoot文件夹下时的配置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath*:applicationContext.xml
   </param-value>
</context-param>

 这样就能解决令人头疼的找不到spring配置文件的位置了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值