为什么我的Spring ContextRefreshed事件被调用了两次?

And*_*dre 19 java spring spring-mvc

我注册了一个Spring ApplicationListener bean来监听ContextRefreshed事件.但是出于一些奇怪的原因,我在完成上下文初始化时得到了对该方法的两次调用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>
Run Code Online (Sandbox Code Playgroud)

谢谢!

sou*_*ica 25

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

  • 或者,如果您@Autowire appContext(或实现ApplicationContextAware),您可以比较该appContext与事件中的appContext. (4认同)