1.定义事件类继承ApplicationEvent抽象类:
import org.springframework.context.ApplicationEvent;
public class RegisterEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
String userName;
public RegisterEvent(Object source, String msg) {
super(source);
this.userName = msg;
}
public String getUserName() {
return userName;
}
}
2.定义监听类实现ApplicationListener接口:
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
@Service
public class RegisterAccountSendMailListener implements
ApplicationListener<RegisterEvent> {
@Override
public void onApplicationEvent(RegisterEvent arg0) {
System.out.println("发邮件到:" + arg0.userName);
}
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class RegisterServices {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.context = arg0;
}
public void register() {
String username = "大大雄";
System.out.println("用户名可以用!");
// do something...
System.out.println("用户注册成功!");
context.publishEvent(new RegisterEvent(this, username));
}
public static void main(String[] args) {
RegisterServices registerServices = new RegisterServices();
registerServices
.setApplicationContext(new ClassPathXmlApplicationContext(
"springEvent/applicationContext.xml"));
registerServices.register();
}
}
加载spring配置文件的时候,Spring框架会将所有的 listener都加载出来,并把它们放在一个集合中。执行 context.publishEvent(new RegisterEvent(this, username));方法是会通过反射找到所有监听了RegisterEvent类的 listener,通过循环执行 listener.onApplicationEvent(event);方法