SpringContext中初始化事件发布者 ###
public
abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {
/** 用于事件发布 */
private ApplicationEventMulticaster applicationEventMulticaster;
/** 静态指定的监听器*/
private Set<ApplicationListener<?>> applicationListeners =
new LinkedHashSet<ApplicationListener<?>>();
public void refresh()
throws BeansException, IllegalStateException {
initApplicationEventMulticaster();
onRefresh();
registerListeners();
}
/**
* 初始化ApplicationEventMulticaster.
* <p>如果在上下文中没有定义,则使用SimpleApplicationEventMulticaster。
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.
class);
if (logger.isDebugEnabled()) {
logger.debug(
"Using ApplicationEventMulticaster [" +
this.applicationEventMulticaster +
"]");
}
}
else {
this.applicationEventMulticaster =
new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug(
"Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" +
this.applicationEventMulticaster +
"]");
}
}
}
/**
* 添加实现ApplicationListener的bean作为监听器
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
/**
*不要在这里初始化FactoryBeans:我们需要将所有常规的bean保留为初始化,以便后bean后置处理器适用于它们!
*/
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.
class,
true,
false);
for (String lisName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(lisName);
}
}
public void publishEvent(ApplicationEvent event) {
Assert.notNull(event,
"Event must not be null");
if (logger.isTraceEnabled()) {
logger.trace(
"Publishing event in " + getDisplayName() +
": " + event);
}
getApplicationEventMulticaster().multicastEvent(event);
if (
this.parent !=
null) {
this.parent.publishEvent(event);
}
}
}
<bean id=
"applicationEventMulticaster" class=
"org.springframework.context.event.SimpleApplicationEventMulticaster">
<!-- 注入任务执行器 这样就实现了异步调用(缺点是全局的,要么全部异步,要么全部同步(删除这个属性即是同步)) -->
<property name=
"taskExecutor" ref=
"executor"/>
</bean>
事件ApplicationEvent
public class EventObject implements java.io.Serializable {
private static final long serialVersionUID =
5516075349620653480L;
/**
* 事件最初发生的对象。
*/
protected transient Object source;
public EventObject(Object source) {
if (source ==
null)
throw new IllegalArgumentException(
"null source");
this.source = source;
}
public Object
getSource() {
return source;
}
public String
toString() {
return getClass().getName() +
"[source=" + source +
"]";
}
}
public abstract class ApplicationEvent extends EventObject {
/** use serialVersionUID from Spring 1.2 for interoperability */
private static final long serialVersionUID =
7099057708183571937L;
/** System time when the event happened */
private final long timestamp;
/**
* Create a new ApplicationEvent.
* @param source the component that published the event (never {@code null})
*/
public ApplicationEvent(Object source) {
super(source);
this.timestamp = System.currentTimeMillis();
}
/**
* Return the system time in milliseconds when the event happened.
*/
public final long getTimestamp() {
return this.timestamp;
}
}
目标(发布事件者)ApplicationEventMulticaster (核心)
public interface ApplicationEventMulticaster {
/**
* 添加一个监听器bean
* @param listener the listener to add
*/
void addApplicationListener(ApplicationListener listener);
/**
* 添加一个监听器的beanName
* @param listenerBeanName the name of the listener bean to add
*/
void addApplicationListenerBean(String listenerBeanName);
/**
* 删除一个监听器bean
* @param listener the listener to remove
*/
void removeApplicationListener(ApplicationListener listener);
/**
* 添加一个监听器beanName
* @param listenerBeanName the name of the listener bean to add
*/
void removeApplicationListenerBean(String listenerBeanName);
/**
* 删除所有在这个Multicaster注册的监听者。
*/
void removeAllListeners();
/**
* 将给定的应用程序事件组播到适当的侦听器。
* @param event the event to multicast
*/
void multicastEvent(ApplicationEvent event);
}
public interface Aware {
}
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory)
throws BeansException;
}
public interface BeanClassLoaderAware extends Aware {
void setBeanClassLoader(ClassLoader classLoader);
}
public abstract class AbstractApplicationEventMulticaster
implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware {
private final ListenerRetriever defaultRetriever =
new ListenerRetriever(
false);
private final Map<ListenerCacheKey, ListenerRetriever> retrieverCache =
new ConcurrentHashMap<ListenerCacheKey, ListenerRetriever>(
64);
private ClassLoader beanClassLoader;
private BeanFactory beanFactory;
public void addApplicationListener(ApplicationListener listener) {
synchronized (
this.defaultRetriever) {
this.defaultRetriever.applicationListeners.add(listener);
this.retrieverCache.clear();
}
}
public void addApplicationListenerBean(String listenerBeanName) {
synchronized (
this.defaultRetriever) {
this.defaultRetriever.applicationListenerBeans.add(listenerBeanName);
this.retrieverCache.clear();
}
}
public void removeApplicationListener(ApplicationListener listener) {
synchronized (
this.defaultRetriever) {
this.defaultRetriever.applicationListeners.remove(listener);
this.retrieverCache.clear();
}
}
public void removeApplicationListenerBean(String listenerBeanName) {
synchronized (
this.defaultRetriever) {
this.defaultRetriever.applicationListenerBeans.remove(listenerBeanName);
this.retrieverCache.clear();
}
}
public void removeAllListeners() {
synchronized (
this.defaultRetriever) {
this.defaultRetriever.applicationListeners.clear();
this.defaultRetriever.applicationListenerBeans.clear();
this.retrieverCache.clear();
}
}
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (
this.beanClassLoader ==
null && beanFactory
instanceof ConfigurableBeanFactory) {
this.beanClassLoader = ((ConfigurableBeanFactory) beanFactory).getBeanClassLoader();
}
}
private BeanFactory
getBeanFactory() {
if (
this.beanFactory ==
null) {
throw new IllegalStateException(
"ApplicationEventMulticaster cannot retrieve listener beans " +
"because it is not associated with a BeanFactory");
}
return this.beanFactory;
}
protected Collection<ApplicationListener>
getApplicationListeners() {
synchronized (
this.defaultRetriever) {
return this.defaultRetriever.getApplicationListeners();
}
}
protected Collection<ApplicationListener>
getApplicationListeners(ApplicationEvent event) {
Class<? extends ApplicationEvent> eventType = event.getClass();
Object source = event.getSource();
Class<?> sourceType = (source !=
null ? source.getClass() :
null);
ListenerCacheKey cacheKey =
new ListenerCacheKey(eventType, sourceType);
ListenerRetriever retriever =
this.retrieverCache.get(cacheKey);
if (retriever !=
null) {
return retriever.getApplicationListeners();
}
if (
this.beanClassLoader ==
null ||
(ClassUtils.isCacheSafe(eventType,
this.beanClassLoader) &&
(sourceType ==
null || ClassUtils.isCacheSafe(sourceType,
this.beanClassLoader)))) {
synchronized (
this.defaultRetriever) {
retriever =
this.retrieverCache.get(cacheKey);
if (retriever !=
null) {
return retriever.getApplicationListeners();
}
retriever =
new ListenerRetriever(
true);
Collection<ApplicationListener> listeners = retrieveApplicationListeners(eventType, sourceType, retriever);
this.retrieverCache.put(cacheKey, retriever);
return listeners;
}
}
else {
return retrieveApplicationListeners(eventType, sourceType,
null);
}
}
/**
* 实际检索给定事件和源类型的应用程序监听器列表。
* @param eventType the application event type
* @param sourceType the event source type
* @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes)
* @return the pre-filtered list of application listeners for the given event and source type
*/
private Collection<ApplicationListener>
retrieveApplicationListeners(
Class<? extends ApplicationEvent> eventType, Class<?> sourceType, ListenerRetriever retriever) {
LinkedList<ApplicationListener> allListeners =
new LinkedList<ApplicationListener>();
Set<ApplicationListener> listeners;
Set<String> listenerBeans;
synchronized (
this.defaultRetriever) {
listeners =
new LinkedHashSet<ApplicationListener>(
this.defaultRetriever.applicationListeners);
listenerBeans =
new LinkedHashSet<String>(
this.defaultRetriever.applicationListenerBeans);
}
for (ApplicationListener listener : listeners) {
if (supportsEvent(listener, eventType, sourceType)) {
if (retriever !=
null) {
retriever.applicationListeners.add(listener);
}
allListeners.add(listener);
}
}
if (!listenerBeans.isEmpty()) {
BeanFactory beanFactory = getBeanFactory();
for (String listenerBeanName : listenerBeans) {
ApplicationListener listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
if (retriever !=
null) {
retriever.applicationListenerBeans.add(listenerBeanName);
}
allListeners.add(listener);
}
}
}
OrderComparator.sort(allListeners);
return allListeners;
}
protected boolean supportsEvent(
ApplicationListener listener, Class<? extends ApplicationEvent> eventType, Class<?> sourceType) {
SmartApplicationListener smartListener = (listener
instanceof SmartApplicationListener ?
(SmartApplicationListener) listener :
new GenericApplicationListenerAdapter(listener));
return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));
}
/**
* Cache key for ListenerRetrievers, based on event type and source type.
* 基于事件类型和源类型的ListenerRetrievers缓存键。
*/
private static class ListenerCacheKey {
private final Class<?> eventType;
private final Class<?> sourceType;
public ListenerCacheKey(Class<?> eventType, Class<?> sourceType) {
this.eventType = eventType;
this.sourceType = sourceType;
}
@Override
public boolean equals(Object other) {
if (
this == other) {
return true;
}
ListenerCacheKey otherKey = (ListenerCacheKey) other;
return ObjectUtils.nullSafeEquals(
this.eventType, otherKey.eventType) &&
ObjectUtils.nullSafeEquals(
this.sourceType, otherKey.sourceType);
}
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(
this.eventType) *
29 + ObjectUtils.nullSafeHashCode(
this.sourceType);
}
}
private class ListenerRetriever {
public final Set<ApplicationListener> applicationListeners;
public final Set<String> applicationListenerBeans;
private final boolean preFiltered;
public ListenerRetriever(
boolean preFiltered) {
this.applicationListeners =
new LinkedHashSet<ApplicationListener>();
this.applicationListenerBeans =
new LinkedHashSet<String>();
this.preFiltered = preFiltered;
}
public Collection<ApplicationListener>
getApplicationListeners() {
LinkedList<ApplicationListener> allListeners =
new LinkedList<ApplicationListener>();
for (ApplicationListener listener :
this.applicationListeners) {
allListeners.add(listener);
}
if (!
this.applicationListenerBeans.isEmpty()) {
BeanFactory beanFactory = getBeanFactory();
for (String listenerBeanName :
this.applicationListenerBeans) {
ApplicationListener listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
if (
this.preFiltered || !allListeners.contains(listener)) {
allListeners.add(listener);
}
}
}
OrderComparator.sort(allListeners);
return allListeners;
}
}
}
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
private Executor taskExecutor;
public SimpleApplicationEventMulticaster() {
}
/**
* Create a new SimpleApplicationEventMulticaster for the given BeanFactory.
*/
public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
setBeanFactory(beanFactory);
}
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
protected Executor
getTaskExecutor() {
return this.taskExecutor;
}
@SuppressWarnings(
"unchecked")
public void multicastEvent(
final ApplicationEvent event) {
for (
final ApplicationListener listener : getApplicationListeners(event)) {
Executor executor = getTaskExecutor();
if (executor !=
null) {
executor.execute(
new Runnable() {
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
}
}
监听器 EventListener
public interface EventListener {
}
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E event);
}