事件通知方
package com.common.event;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import com.common.web.AppContext;
public class EventSource {
protected Class<? extends EventListener<?>> listenerIntf;
public EventSource(Class<? extends EventListener<?>> listenerIntf){
if (listenerIntf == null){
throw new IllegalArgumentException("ListenerIntf should not be null!");
}
String baseListenerPackageName = EventListener.class.getPackage().getName();
if (listenerIntf.getCanonicalName().equals(baseListenerPackageName + ".EventListener")){
throw new IllegalArgumentException("Module business should define it's own EventListener!");
}
this.listenerIntf = listenerIntf;
}
public EventSource(){
}
public void sendNotify() {
ApplicationContext applicationContext = AppContext.getContext();
if (listenerIntf == null){
throw new NullPointerException("listenerIntf should not null!");
}
Map<String, ?> map = applicationContext.getBeansOfType(listenerIntf);
if (map != null && !map.isEmpty()){
Collection<?> classes = map.values();
Iterator<?> iterator = classes.iterator();
while (iterator.hasNext()){
@SuppressWarnings("unchecked")
EventListener<EventSource> listener = (EventListener<EventSource>)iterator.next();
listener.handleEvent(this);
}
}
}
}
事件接收方:
public interface EventListener<T extends EventSource> extends java.util.EventListener {
public void handleEvent(T eventSource);
}