日常有很多项目再启动的时候,需要初始化一些数据做缓存,部署启动时一般情况下的初始化容器加载:
package com.example.demo.common; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class KafkaStartListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("初始化加载!"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
整合到spring boot 部署:只需要添加@ServletComponentScan注解,就会在spring boot 部署初始化时加载
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }