ApplicationListener调用过程详解:
实现接口ApplicationListener,并重写public void onApplicationEvent(ApplicationEvent event) {}可以在容器初始话的时候执行这个方法,其中源码为:
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.EventListener;
/**
* Interface to be implemented by application event listeners.
* Based on the standard {@code java.util.EventListener} interface
* for the Observer design pattern.
*
* <p>As of Spring 3.0, an ApplicationListener can generically declare the event type
* that it is interested in. When registered with a Spring ApplicationContext, events
* will be filtered accordingly, with the listener getting invoked for matching event
* objects only.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @param <E> the specific ApplicationEvent subclass to listen to
* @see org.springframework.context.event.ApplicationEventMulticaster
*/
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}
事件类型:
1、ApplicationContextEvent
是spring内置事件的父抽象类,构造方法传入spring的context容器,同时也有获取spring的context容器的方法。
2、ContextRefreshedEvent
当spring容器初始化或刷新时,会触发此事件。此事件在开发中常用,用于在spring容器启动时,导入自定义的bean实例到spring容器中。
3、ContextStartedEvent
当spring启动时,或者说是context调用start()方法时,会触发此事件。
4、ContextStoppedEvent
当spring停止时,或者说context调用stop()方法时,会触发此事件。
5、ContextClosedEvent
当spring关闭时,或者说context调用close()方法时,会触发此事件。
实际项目中根据需求使用对应事件:
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import com.jh.ta.scheduler.Scheduler;
/**
* <br/>
* Author:杨杰超<br/>
* Date:2018年10月28日 下午9:18:05 <br/>
* Copyright (c) 2018, yangjiechao@dingtalk.com All Rights Reserved.<br/>
*
*/
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// 初始化完成后. 执行一次同步系统参数
Scheduler scheduler = contextRefreshedEvent.getApplicationContext().getBean(Scheduler.class);
scheduler.syncSysParam();
}
}
可以在ApplicationStartup中添加类注解@Component,让spring容器管理起来。
或者在springboot启动类中手动添加listeners
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.addListeners(new ApplicationStartup());
app.run(args);
}
2种方式皆可,