spring4.2.9 java项目环境下ioc源码分析 (十五)——refresh之registerListeners方法

注册监听器,与广播器是同时存在的。在广播器章节,spring只是初始化的广播器,但是并没有为广播器绑定Listener。Spring在此方法中进行了绑定。

下面看代码

protected void registerListeners() {
		// 和手动注册BeanPostProcess一样,可以自己通过set手动注册监听器
		for (ApplicationListener listener : getApplicationListeners()) {
			//手动注册的监听器绑定到广播器
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		//取到监听器的名称,设置到广播器
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		// 如果存在早期应用事件,发布
		Set earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

但是对于spring配置的监听器,spring在这里貌似并没有做处理,只是设置的名字。其实不是没有设置,还记得前几章讲到的BeanPostProcess么,spring注册了一个ApplicationListenerDetector的后置处理器,这个后置处理器就是用来向广播器绑定监听器的。只是这是在初始化bean的时候用到的。

下面是个例子:

自定义事件,继承ApplicationEvent,需要重写构造

public class TestEvent extends ApplicationEvent{

	private User user;

	public TestEvent(Object source,User user) {
		super(source);
		this.user=user;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}

自定义监听,实现ApplicationListener接口,重写方法

public class TestListener implements ApplicationListener{

	public void onApplicationEvent(TestEvent event) {
		User user = event.getUser();
		System.out.println(user.getEmail());
	}

}

配置文件中配置监听器

上下文去发布

MyApplicationContext context=new MyApplicationContext("classpath:APP/CONTEXT/applicationContext-text.xml");
		//TestListener user=(TestListener)context.getBean("testListener");
		User user=new User();
		user.setEmail("1111");
		context.publishEvent(new TestEvent("", user));
结果会打印user的邮箱


你可能感兴趣的:(spring,ioc)