ServletContextListener是servlet容器中的一個API接口, 它用來監聽ServletContext的生命周期,也就是相當于用來監聽Web應用的生命周期。
使用配置如下
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
@Component
@Slf4j
public class DateServer implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
log.info("liting: contextDestroyed");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
log.info("liting: contextInitialized");
}
}
需要在啟動類中增加@ServletComponentScan 注解
@ServletComponentScan
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(AnranpslsApplication.class, args);
}
}
但是使用中可能會出現idea内置tomcat啟動成功,配置外部tomcat啟動時報錯,或打包war部署到外部tomcat後啟動成功,通路不了程式。項目中我改用了實作ApplicationRunner 接口實作 tomcat啟動時應用程式。
代碼如下:
@Slf4j
@Component
@Order(value = 1)
public class MyServletContextListener implements ApplicationRunner {
@Resource
public FaceRecognitionService faceRecognitionService;
//實際需要上的靜态屬性
public static FaceRecognitionService sFaceRecognitionService;
@PostConstruct
public void init() {
sFaceRecognitionService = this.faceRecognitionService;
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("應用程式啟動");
}
}
通過實作run方法實作要操作的方法。
說明@Order(value=1) 配置啟動順序,數字越小啟動優先級越高。