2014-04-27 30 views

回答

13

使用類似下面的代碼:

@Component 
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> { 

    @Override 
    public void onApplicationEvent(final ContextRefreshedEvent event) { 
    // do your stuff here 
    } 
} 

當然StartupListener將需要在組件中掃描的達到

採取不過請注意,如果您的應用程序使用多個上下文(例如根上下文和一個web上下文),這個方法將針對每個上下文運行一次。

4

你可以寫聽衆是這樣的:

@Component 
public class SpringContextListener implements ApplicationListener<ApplicationEvent> { 
    public void onApplicationEvent(ApplicationEvent arg0) { 
     System.out.println("ApplicationListener"); 
    }; 
} 

只需添加組件掃描路徑是這樣的:

<context:component-scan base-package="com.controller" /> 
4

看一看Better application events in Spring Framework 4.2

@Component 
public class MyListener { 

    @EventListener 
    public void handleContextRefresh(ContextRefreshedEvent event) { 
     ... 
    } 
} 

註釋的方法使用@EventListener自動註冊與簽名匹配的ApplicationListener的方法。 @EventListener是一個核心註釋,它以與@Autowired等類似的方式進行透明處理:對於java config和現有的上下文:annotation-driven />元素不需要額外的配置就可以完全支持它。

相關問題