[英]How can I declare a startup-hook in a Java Web App
我想在啟動Web應用程序時進行一些初始化(計時器和日志記錄)。 我無法使用ContextListener,因為我沒有在其中獲得任何Spring組件。 我需要一個簡單的鈎子,例如“ afterWebAppHasLoadedAndEverythingyIsSetUp()”。 是否存在?
加載bean時,ApplicationContext發布某些類型的事件。
通過ApplicationEvent類和ApplicationListener接口提供ApplicationContext中的事件處理。 因此,如果bean實現了ApplicationListener,則每次將ApplicationEvent發布到ApplicationContext時,都會通知該bean。
春季提供以下活動
首先創建一個ApplicationListener的實現,如下所示
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class CStartEventHandler
implements ApplicationListener<ContextStartedEvent>{
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent Received");
}
}
然后,您只需在Spring中將類注冊為bean。
如果您使用的是Spring Boot(我建議使用),則可以在應用程序啟動后使用以下CommandLineRunner bean運行初始化內容。 您將可以准備好所有的四季豆,下面是代碼片段。
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {
// here you can take any number of object which is anutowired automatically
@Bean
public CommandLineRunner init(MyService service, MyRepository repository) {
// do your stuff with the beans
return null;
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.