如何在Java Web App中声明启动挂钩

时间:2017-01-24 19:13:10

标签: java spring servlets

我想在启动Web应用程序时进行一些初始化(计时器和日志记录)。我不能使用ContextListener,因为我没有得到任何我的Spring-Components。我需要一个简单的钩子,比如“afterWebAppHasLoadedAndEverythingyIsSetUp()”。 它存在吗?

2 个答案:

答案 0 :(得分:2)

ApplicationContext在加载bean时发布某些类型的事件。

ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicationListener接口提供的。因此,如果bean实现了ApplicationListener,那么每次将ApplicationEvent发布到ApplicationContext时,都会通知该bean。

以下事件由spring提供

  • ContextRefreshedEvent
  • ContextStartedEvent
  • ContextStoppedEvent
  • ContextClosedEvent

首先按如下所示创建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。

答案 1 :(得分:1)

如果您使用的是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);
    }
}