tomcat啓動完成執行 某個方法 定時任務(Spring)

第一步引入接口: 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>
相關文章
相關標籤/搜索