Spring事件框架

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);

	}

}


3.测试类:

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);方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值