[JAVA]SpringBoot整合Listener
1.注解形式
很简单,添加@WebListener()即可。
package xyz.xioaxin12.springboot.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener()
public class MyListener implements ServletContextListener{
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("listener...init......");
    }
}
启动类
添加@ServletComponentScan就行了。
package xyz.xioaxin12.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import xyz.xioaxin12.springboot.listener.MyListener;
@SpringBootApplication
@ServletComponentScan
public class SpringBoot02FilterApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot02FilterApplication.class, args);
    }
}
这样在项目启动的时候就会打印listener…init……
2.方法注册
1).删除MyListener上的注解。
2).修改启动类。
在原启动类上添加如下代码即可!
@Bean                                                                                                                      
public ServletListenerRegistrationBean<MyListener> getListenerServletListenerRegistrationBean(){                           
    ServletListenerRegistrationBean<MyListener> bean = new ServletListenerRegistrationBean<MyListener>(new MyListener());  
   return bean;                                                                                                            
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 xiaoxin1218@qq.com
文章标题:[JAVA]SpringBoot整合Listener
文章字数:206
本文作者:周信
发布时间:2019-10-22, 22:39:00
最后更新:2023-05-03, 10:25:35
原始链接:http://zx21.xyz/2019/10/22/JAVA-SpringBoot整合Listener/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。
 
            