第一步引入接口: ServletContextListener
@RestController @RequestMapping("/schedule") public class ScheduleController implements ServletContextListener { @Autowired private ScheduleService scheduleService; @Override public void contextDestroyed(ServletContextEvent event) { System.out.println("銷毀"); } @Override public void contextInitialized(ServletContextEvent event) { WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext()) .getAutowireCapableBeanFactory().autowireBean(this); System.out.println("開始執行周期任務"); scheduleService.start(); ; } }
如下圖:
第二步:在web.xml文件中配置監聽
<listener> <listener-class>com.wbg.treasure.controller.ScheduleController</listener-class> </listener>