1、MyServletContextListener 实现(implements) ServletContextListener 创建监听器。
    image.png

    1. package com.wzy.springbootweb02.servlet;
    2. import lombok.extern.slf4j.Slf4j;
    3. import javax.servlet.ServletConfig;
    4. import javax.servlet.ServletContextEvent;
    5. import javax.servlet.ServletContextListener;
    6. import javax.servlet.annotation.WebListener;
    7. @Slf4j
    8. @WebListener
    9. public class MyServletContextListener implements ServletContextListener {
    10. @Override
    11. public void contextInitialized(ServletContextEvent sce) {
    12. log.info("MyServletContextLister监听到项目初始化完成。");
    13. }
    14. @Override
    15. public void contextDestroyed(ServletContextEvent sce) {
    16. log.info("MyServletContextLister监听到项目销毁。");
    17. }
    18. }

    2、在启动类上面加上扫描注解 @ServletComponentScan``(basePackages = ``"com.wzy.springbootweb02.servlet"``) 扫描Servlet程序。

    1. package com.wzy.springbootweb02;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.boot.web.servlet.ServletComponentScan;
    5. @ServletComponentScan(basePackages = "com.wzy.springbootweb02.servlet")
    6. @SpringBootApplication
    7. public class SpringbootWeb02Application {
    8. public static void main(String[] args) {
    9. SpringApplication.run(SpringbootWeb02Application.class, args);
    10. }
    11. }