Spring Boot的listener(监听器)简单使用实例详解
监听器(Listener)的注册方法和Servlet一样,有两种方式:代码注册或者注解注册
1.代码注册方式
通过代码方式注入过滤器
@Bean publicServletListenerRegistrationBeanservletListenerRegistrationBean(){ ServletListenerRegistrationBeanservletListenerRegistrationBean=newServletListenerRegistrationBean(); servletListenerRegistrationBean.setListener(newIndexListener()); returnservletListenerRegistrationBean; }
IndexListener.Java类:
packagecom.example.Listener; importjavax.servlet.ServletContextEvent; importjavax.servlet.ServletContextListener; publicclassIndexListenerimplementsServletContextListener{ @Override publicvoidcontextDestroyed(ServletContextEventarg0){ System.out.println("IndexListenercontextDestroyedmethod"); } @Override publicvoidcontextInitialized(ServletContextEventarg0){ System.out.println("IndexListenercontextInitializedmethod"); } }
2.注解方式
通过注解方式注入过滤器
IndexListener2.Java类
packagecom.example.Listener; importjavax.servlet.ServletContextEvent; importjavax.servlet.ServletContextListener; importjavax.servlet.annotation.WebListener; @WebListener publicclassIndexListener2implementsServletContextListener{ @Override publicvoidcontextDestroyed(ServletContextEventarg0){ System.out.println("IndexListener2contextDestroyedmethod"); } @Override publicvoidcontextInitialized(ServletContextEventarg0){ System.out.println("IndexListener2contextInitializedmethod"); } }
把注解加到入口处启动即可
@SpringBootApplication @ServletComponentScan publicclassSpringBootSimpleApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(SpringBootSimpleApplication.class,args); } }
以上所述是小编给大家介绍的SpringBoot的listener(监听器)简单使用实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!