【问题标题】:Why is my Spring ContextRefreshed event called twice?为什么我的 Spring ContextRefreshedevent 被调用了两次?
【发布时间】:2011-09-04 02:35:30
【问题描述】:

我注册了一个 Spring ApplicationListener bean 来监听 Co​​ntextRefreshed 事件。不过,出于某种奇怪的原因,我在上下文初始化完成时收到了对onApplicationEvent(ContextRefreshedEvent) 方法的两次 调用。这是正常行为还是表明我的配置有问题?我将 Jetty 8 用于我的 Servlet 容器。

我的相关web.xml配置如下

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/spring/spring-config.xml</param-value>
</context-param>
<servlet>
    <servlet-name>Spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
    <servlet-name>Spring</servlet-name>
    <url-pattern>/service/*</url-pattern>
</servlet-mapping>

谢谢!

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    即使您没有为 DispatcherServlet 指定 contextConfigLocation,它仍然会创建一个子上下文,并且第二个刷新事件是针对该上下文的。使用 event.getApplicationContext() 找出事件的上下文。

    【讨论】:

    • 就是这样!使用 ApplicationContext 的 iddisplayName 属性,我现在可以区分这两个事件。
    • 或者,如果您 @Autowire appContext(或实现 ApplicationContextAware),您可以将 appContext 与事件中的 appContext 进行比较。
    • @Andre 一个菜鸟的问题:如何从 ContextRefreshedEvent 访问 ID 或 displayName?
    • 想通了。通过将 ContextRefreshedEvent.getSource() 转换为 ApplicationContext,然后在其上调用 getDisplayName()/getId()。
    【解决方案2】:

    它也发生在我身上,在不同的事件监听器上。 (ApplicationListener&lt;AuthenticationFailureBadCredentialsEvent&gt;)

    我怀疑是 ContextLoaderListener,当我从 web.xml 中删除声明时,应用程序运行正常。然后我必须弄清楚它的目的是什么,ContextLoaderListener...

    Role/Purpose of ContextLoaderListener in Spring?

    有趣的答案是:

    ContextLoaderListener 是可选的。只是在这里说明一点:你可以 无需配置即可启动 Spring 应用程序 ContextLoaderListener ...只是最基本的 web.xml DispatcherServlet

    【讨论】:

      【解决方案3】:

      它看起来像错误。

      https://jira.springsource.org/browse/SPR-6589

      如果您使用的是 3.0,请尝试最新的可用版本 3.05。

      【讨论】:

      • 好的,我们正在使用 3.0.4,所以我会试一试 3.0.5 并报告我的发现。
      • 呸,升级到 3.0.5 还是有问题。
      • 即使是 3.1 也有同样的问题。
      【解决方案4】:

      我也遇到了这个问题,但已经解决了。我正在将数据源注入我的 DAO(并用它实例化一个 JdbcTemplate)......但我也为 JDBCTemplate 配置了一个 Spring bean。

      我应该用 jdbcTemplate 注入我的 DAO...以避免重复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 2013-11-20
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-31
        相关资源
        最近更新 更多