Why is my Spring ContextRefreshed event called twi

2019-01-11 17:52发布

问题:

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!

回答1:

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.



回答2:

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



回答3:

It looks like bug.

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

If you are using 3.0 try it on the latest available release which is 3.05.



回答4:

I had this problem too but fixed it. I was injecting the dataSource into my DAO (and instantiating a JdbcTemplate with it)....but I also had a Spring bean configured for JDBCTemplate.

I should have been injecting my DAO with the jdbcTemplate...that avoids the duplicate.