2011-05-28 130 views
15

我有一個Spring ApplicationListener bean註冊來偵聽ContextRefreshed事件。但由於某種奇怪的原因,我在上下文初始化完成後得到了兩個調用onApplicationEvent(ContextRefreshedEvent)方法。這是正常行爲還是表示配置有問題?我爲我的Servlet容器使用Jetty 8。爲什麼我的Spring ContextRefreshed事件被調用兩次?

我相關的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> 

謝謝!

回答

23

即使您沒有爲您的DispatcherServlet指定contextConfigLocation,它仍會創建一個子上下文,而第二個刷新事件是針對該上下文的。使用event.getApplicationContext()來找出事件的上下文。

+1

就是這樣!現在我可以使用ApplicationContext的'id'或'displayName'屬性來區分這兩個事件。 – Andre 2011-05-29 13:06:00

+3

或者,如果您@Autowire appContext(或實現ApplicationContextAware),您可以比較該appContext與事件中的那個。 – sourcedelica 2011-05-29 23:32:23

+0

@Andre一個noob的問題:如何從ContextRefreshedEvent訪問ID或displayName? – 2015-11-27 14:39:36

1

它看起來像bug。

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

如果您使用的3.0試試最新的可用版本是3.05。

+0

好吧,我們使用3.0.4所以我基本最低web.xml中的Spring應用程序我會給3.0.5一個鏡頭並報告我的發現。 – Andre 2011-05-29 00:18:59

+0

Bah,升級到3.0.5,這仍然是一個問題。 – Andre 2011-05-29 00:58:08

+0

甚至3.1也有同樣的問題。 – Deckard 2013-05-31 09:12:38

1

我也有這個問題,但修復它。我正在將dataSource注入到DAO中(並用它實例化一個JdbcTemplate)......但我也爲JDBCTemplate配置了一個Spring bean。

我應該注入我的DAO與jdbcTemplate ...,避免重複。

2

它發生在我身上,在不同的事件監聽器上。 (ApplicationListener<AuthenticationFailureBadCredentialsEvent>

我懷疑ContextLoaderListener,當我從web.xml中刪除聲明時,該應用程序正常工作。然後,我不得不弄清楚什麼是它的目的,的ContextLoaderListener的...

Role/Purpose of ContextLoaderListener in Spring?

有趣的答案有:

的ContextLoaderListener是可選的。只是提出一個觀點在這裏:你可以 開機而沒有配置 的ContextLoaderListener ......只是 的DispatcherServlet

相關問題