SpringBoot自定义初始化Listener配置

版权声明:欢迎转载,请注明作者和出处 https://blog.csdn.net/baichoufei90/article/details/84032563

SpringBoot自定义初始化Listener配置

0x01 摘要

在传统的以Spring-Web程序中,我们会继承ContextLoaderListener来实现一些早期运行的初始化代码。但是现在迁移到Spring-Boot后发现不能这么做了。本文讲讲在SpringBoot中怎么配置Listener。

0x02 ServletContextListener

ServletContextListener是依赖于Servlet容器的。

2.1 Listener配置

Listener改为实现ServletContextListener,还要在类上加@WebListener注解。其余可以不动:

/**
 * Created by chengc on 2018/5/7.
 */
@WebListener
public class DoveInitListener
        implements ServletContextListener
{
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //do something while contextInitialized
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //do something while contextDestroyed
    }
}
  • contextInitialized
    用来通知监听器web应用初始化过程已经开始。
    在所有filterservlet初始化前会通知所有实现了ServletContextListener的对监听器。
  • contextDestroyed
    用来通知servletContext即将关闭。
    在通知所有ServletContextListener监听器servletContext销毁之前,所有servletfilter都已被销毁。

2.2 SpringBoot启动类配置

只需要在SpringBoot 启动类中加上@ServletComponentScan注解即可

@ServletComponentScan
@SpringBootApplication
public class SpringbootServer extends SpringBootServletInitializer
{
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(SpringbootServer.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringbootServer.class, args);
	}
}

0x03 ApplicationListener

ApplicationListener依赖于Spring。

在普通Spring应用中一般监听ContextRefreshedEvent事件。而在Spring Boot中可以监听多种事件,比如:

  • ApplicationStartedEvent:spring boot启动监听类
  • ApplicationEnvironmentPreparedEvent:环境事先准备
  • ApplicationPreparedEvent:上下文context准备时触发
  • ApplicationReadyEvent:上下文已经准备完毕的时候触发
  • ApplicationFailedEvent:该事件为spring boot启动失败时的操作

ApplicationListener一般用于spring容器初始化完成之后,执行需要处理的一些操作,比如一些数据的加载、初始化缓存、特定任务的注册等等。

示例如下:

@Service
public class AppListener implements ApplicationListener {
   @Autowired
    private UserMapper userMapper;
 
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    	//基于ApplicationListener的监听器的onApplicationEvent方法可能会被执行多次,所以需要添加以下判断:
        if(event.getApplicationContext().getParent() == null){
	        System.out.println("*************ApplicationListener<ContextRefreshedEvent> start************");
	 
	        User user2 = userMapper.selectByUsername("zifangsky");
	        System.out.println(JsonUtils.toJson(user2));
        }
    }

0xFF 更多参考文档

浅析servlet的ServletContextListener与Spring的ApplicationListner

Spring中的ApplicationListener和ServletContextListener的区别

猜你喜欢

转载自blog.csdn.net/baichoufei90/article/details/84032563
今日推荐