Spring源码拜读之Spring的事件驱动

  1. 入口 
ContextLoaderListener 底层使用java.util.EventListener (Java中的事件机制,也就是观察者模式)

java中的事件机制的参与者有3种角色:

1.event object:事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中

2.event source:具体的事件源,比如说,你点击一个button,那么button就是event source,要想使button对某些事件进行响应,你就需要注册特定的listener。(被观察者)

3.event listener:对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,这个接口要继承 java.util.EventListener。 实现了事件监听者接口中一些或全部方法的类就是事件监听者。(观察者)

ApplicationEvent

/**
 * @author lichenyang8
 * @date 2019/6/17
 */
public class MyEvent extends ApplicationEvent {
    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public MyEvent(Object source) {
        super(source);
    }
}

ApplicationListener

package com.jd.ept.open.man.event;

import org.springframework.context.ApplicationListener;

/**
 * @author lichenyang8
 * @date 2019/6/17
 */
public class MyListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(MyEvent event) {
        int s= 1/0;
        System.out.println("listener my event,content: " + event.getSource());
    }

}

ErrorHandler(异常回调的实现)

package com.jd.ept.open.man.event;

import org.springframework.util.ErrorHandler;

/**
 * @author lichenyang8
 * @date 2019/6/17
 */
public class MyErrorHandler implements ErrorHandler {
    @Override
    public void handleError(Throwable t) {
        System.out.println(t.getClass());
        System.out.println(t.getMessage());
    }
}

spring-context.xml

    

    
    
        
            5
        
    
    
    
        
        
    
    
    

    

main

package com.jd.ept.open.man.event;

import com.jd.ept.open.man.service.impl.SysConfigServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author lichenyang8
 * @date 2019/6/17
 */
public class TestMain {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        context.publishEvent(new MyEvent("init"));
        SysConfigServiceImpl sysConfigServiceImpl = (SysConfigServiceImpl) context.getBean("sysConfigServiceImpl");
        System.out.println(sysConfigServiceImpl);
    }
}

 

你可能感兴趣的:(技术,Spring源码学习)