为什么我的春季背景刷新事件被调用两次?

2022-09-01 23:16:51

我有一个注册了Spring ApplicationListener bean来侦听 ContextRefreshed 事件。但是,由于一些奇怪的原因,我在上下文初始化完成时获得了对该方法的次调用。这是正常行为还是表明我的配置存在问题?我正在使用Jetty 8作为我的Servlet容器。onApplicationEvent(ContextRefreshedEvent)

我的相关网页.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>

谢谢!


答案 1

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


答案 2

它也发生在我身上,在另一个事件监听器上。(ApplicationListener<AuthenticationFailureBadCredentialsEvent>)

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

ContextLoaderListener在春季的角色/目的?

有趣的答案是:

ContextLoaderListener 是可选的。只是为了在这里提出一个观点:你可以启动一个Spring应用程序,而无需配置ContextLoaderListener ...只是基本的最小web.xml与调度程序Servlet


推荐