当前位置: 代码网 > it编程>编程语言>Java > Spring中配置ContextLoaderListener方式

Spring中配置ContextLoaderListener方式

2025年04月12日 Java 我要评论
spring中配置contextloaderlistenerweb.xml: <!-- contextconfiglocation参数用来指定spring的配置文件 needed for co

spring中配置contextloaderlistener

web.xml:

  <!-- contextconfiglocation参数用来指定spring的配置文件 needed for contextloaderlistener -->
    <context-param>
        <param-name>contextconfiglocation</param-name>
        <param-value>classpath:spring-persist-*.xml</param-value>
    </context-param>

    <!-- 配置spring核心监听器 bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
    </listener>

contextloaderlistener的作用是什么?

contextloaderlistener的作用就是启动web容器时,读取在contextconfiglocation中定义的xml文件,自动装配applicationcontext的配置信息,并产生webapplicationcontext对象,然后将这个对象放置在servletcontext的属性里,这样我们只要得到servlet就可以得到webapplicationcontext对象,并利用这个对象访问spring容器管理的bean。

简单来说,就是上面这段配置为项目提供了spring支持,初始化了ioc容器。

web.xml 中 contextloaderlistener 是否可以不配置?

  • 如果只有 spring mvc 的一个 servlet,listener 可以不用。
  • 但是如果用了shiro 等,shiro 用到的 spring 的配置必须在 listener 里加载。
  • 一般 dao, service 的 spring 配置都会在 listener 里加载,因为可能会在多个 servlet 里用到,而且父子 context 间存在可见性问题,所以,为了防止重复加载需要在 listener 中进行加载。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com