我和春天有个约会(二)

来源:互联网 发布:数据库通讯协议 编辑:程序博客网 时间:2024/04/27 03:07
 
偷了两天懒,惭愧,毛主席说了,“一万年太久,只争朝夕”。
Bean容器服务
剪不断,理还乱……
Spring优势之一就是No-Intrusive,使应用逻辑意识不到Spring框架的存在,从而利于系统移植性的提升。但框架还是提供了一组服务/API为应用提供方便,当然了,要是用了这些,你就逃不掉了,谈不上“非入侵”了,就是Spring的人了。
这组服务用于几个方面:在Bean的生命周期阶段中提供用户定制接口;为方便资源获取提供接口;提供更丰富的依赖注入方式;提供监听-事件机制。
我最感兴趣的就是事件机制的支持,就拿它开刀。这套机制有四个组成部分:(1)事件,从org.springframework.context.ApplicationEvent派生;(2)监听者,实现了org.springframework.context.ApplicationListener接口;(3)配制文件对监听者的声明;(4)事件的发布者。
事件类以统一的接口包装了传向事件监听者的对象,也就是这里的source。
public class MyEvent extends ApplicationEvent{
    
public MyEvent(Object source) {
        
super(source);
        System.out.println(
"MyEvent:" + source);
    }

}

  
监听者用于当事件发布时提供回应,回应方式就是接口中的onApplicationEvent方法立刻得到调用,方法参数则是event对source的包装,待进入onApplicationEvent方法则还source以本来面目。
 
public class MyListener implements ApplicationListener {
    
public MyListener() {
        System.out.println(
"MyListener constructs...");
    }


    
public void onApplicationEvent(ApplicationEvent event) {
        
if (event instanceof MyEvent) {
            System.out.println(
"MyListener:" + event.getSource());
        }
 else {
            System.out.println(
"OtherListener:" + event);
        }

    }


}

 
配置文件需对listener留上一笔:
<bean id="listen" class="onlyfun.caterpillar.event.MyListener"/>
 
事件的发布过程为:
public static void main(String[] args) {
        System.out.println(
"Before loading the context...");
        ApplicationContext context 
= new ClassPathXmlApplicationContext(
                
"beanevent-config.xml");
        System.out.println(
"Be ready to publish...");
        context.publishEvent(
new MyEvent(new MainTest()));
        System.out.println(
"After publishing...");
    }

 
运行结果如下:
Before loading the context...
MyListener constructs...
OtherListener:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@3bb2b8: display name [org.springframework.context.support.ClassPathXmlApplicationContext@3bb2b8]; startup date [Fri Jun 15 22:26:42 CST 2007]; root of context hierarchy]
Be ready to publish...
MyEvent:onlyfun.caterpillar.event.MainTest@a613f8
MyListener:onlyfun.caterpillar.event.MainTest@a613f8
After publishing...
 
可见当ApplicationContext加载配制文件后,listener得到构造并处于某种“循环”等待当中(令我想起Windows的message处理),对event来者不拒,所以在onApplicationEvent中需要分门别类,意外得到的信息就是ClassPathXmlApplicationContext也成为source被打包进了Event(ContextRefreshedEvent)光顾了MyListener
发布的过程是创建event,在其中包装要传递的source对象,调用publishEvent发布,listener立马回应,指哪儿打哪儿,真听话。
下一回,期待已久的AOP……
原创粉丝点击