Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Spring ContextRefreshed event called twice?

Tags:

I have a Spring ApplicationListener bean registered to listen for ContextRefreshed events. For some odd reason though, I get two calls to the onApplicationEvent(ContextRefreshedEvent) method at the completion of the context initialization. Is this normal behavior or is it indicative of a problem with my configuration? I'm using Jetty 8 for my Servlet container.

My relevant web.xml configuration is as follows

<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> 

Thanks!

like image 879
Andre Avatar asked May 28 '11 21:05

Andre


2 Answers

Even though you did not specify a contextConfigLocation for your DispatcherServlet it still creates a child context and the second refreshed event is for that context. Use event.getApplicationContext() to find out which context the event is for.

like image 188
sourcedelica Avatar answered Oct 17 '22 07:10

sourcedelica


it happened to me as well, on a different event-listener. (ApplicationListener<AuthenticationFailureBadCredentialsEvent>)

I suspected the ContextLoaderListener, and when I removed the declaration from the web.xml, the app was working properly. Then I had to figure out what is its purpose, of the ContextLoaderListener...

Role/Purpose of ContextLoaderListener in Spring?

the interesting answer there is:

ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring application without ever configuring ContextLoaderListener ...just the basic minimum web.xml with DispatcherServlet

like image 34
OhadR Avatar answered Oct 17 '22 06:10

OhadR