标签:web SpringBoot sce void Listener 整合 注解 public
在传统的web开发时,我们创建一个Listener,需要在web.xml里做配置:
<listener> <listener-class>com.linhw.demo.listener.MyFirstListener</listener-class> </listener>
这样每新增一个Listener类都要在web.xml增加一段类似的配置,很繁琐,降低了开发的效率。
SpringBoot提供了两种方式来解决整个问题:
- 通过注解扫描完成 Listener 组件的注册
- 通过方法完成 Listener 组件注册
引入依赖:
<!-- 核心启动器, 包括auto-configuration、logging and YAML --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- building web, including RESTful, applications using Spring MVC. 使用Tomcat作为嵌入式容器, @RestController由这个starter提供--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
一、通过注解扫描完成 Listener 组件的注册
@WebListener public class MyFirstListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //启动时,在控制台可以看到 System.out.println("MyFirstListener...init......"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
使用注解的方式必须在SpringBoot启动类增加@ServletComponentScan注解,这样SpringBoot 启动时会扫描@WebListener,实例化这些类。
二、通过方法完成 Listener 组件注册
/** * 与第一种方式的区别,就是没有加@WebListener注解 */ public class MySecondListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //启动时,在控制台可以看到 System.out.println("MySecondListener Listener...init......"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
这种方式需要在配置类上以@Bean的形式注入到Spring容器中。
@Configuration public class BootConfig { /** * 添加@Bean将名为"getListener"的bean加入到容器中 */ @Bean public ServletListenerRegistrationBean<MySecondListener> getListener(){ ServletListenerRegistrationBean<MySecondListener> secondLisener = new ServletListenerRegistrationBean<MySecondListener>(new MySecondListener()); return secondLisener; } }
标签:web,SpringBoot,sce,void,Listener,整合,注解,public 来源: https://www.cnblogs.com/myitnews/p/12346406.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。