Spring4-在Web应用程序中使用Spring

Spring可以在非Web应用程序中使用

由于Web应用程序入口是被Web服务器控制的,所以无法在main()方法中通过创建ClassPathXmlApplicationContext对象来启动Spring容器.
Spring提供了一个监听类org.srpingframework.web.context.ContextLoaderListener来解决这个问题.该监听器实现了ServletContextListener接口,可以在Web容器启动的时候初始化Spring容器.
web.xml配置

    <!-- 配置环境参数,指定Spring配置文件的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/Spring-*.xml</param-value>
    </context-param>
    <!-- 配置Spring的ContextLoaderListener监听器,初始化Spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

其中,contextConfigLocation参数用来指定Spring配置文件的路径.可以写文件全名,也可以想我一样使用"星号"通配符来加载多个spring的配置文件.

如果没有指定 contextConfigLocation 参数,ContextLoaderListener默认会查找/WEB-INF/applicationContext.xml.换句话说,如果我们将Spring 的配置文件命名为applicationContext.xml并放在WEB-INF目录下,即使不指定
contextConfigLocation参数,也能实现配置文件的加载.

注意:contextConfigLocationContextLoaderListener类的属性.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,437评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,251评论 6 342
  • (一)Struts、Spring、Hibernate、Mybatis框技术 1.Struts2.0有几种标签库 【...
    独云阅读 3,370评论 0 62
  • Spring容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof阅读 2,912评论 1 24
  • 当别人拥有,而你没有时,不要一味地羡慕,嫉妒,甚至“恨”,因为你的确有不足!
    达96阅读 235评论 0 0

友情链接更多精彩内容