`
zhangcong170
  • 浏览: 69735 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

Spring笔记

    博客分类:
  • j2ee
阅读更多

      最近正在学习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配置文件的位置了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics