说到设计模式不得不提设计原则,可以说设计模式就是遵循着设计原则尔孕育而出的。
观察者模式
这里简单介绍一下观察者模式
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
//自定义一个自己的事件原
public class MyEvent extends ApplicationContextEvent {
//自定义的事件原内部可以第一成员变量
private String eventSource;
public MyEvent(ApplicationContext source,String eventSource ) {
super(source);
this.eventSource = eventSource;
System.out.println("MyEvent~~~~~~~~~~" + eventSource);
}
public String getEventSource() {
return eventSource;
}
public void setEventSource(String eventSource) {
this.eventSource = eventSource;
}
}
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//定义监听者01,监听MyEvent事件
@Component
public class SaveEvent implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent myEvent) {
System.out.println("SaveEvent事件监听到了MyEvent~~~~~~~"+myEvent.getEventSource());
}
}
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//定义监听者02,监听MyEvent事件
@Component
public class InsetEvent implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent myEvent) {
System.out.println("InsetEvent事件监听到了MyEvent~~~~~~~"+myEvent.getEventSource());
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class EventTestService {
@Autowired
ApplicationContext applicationContext;
public void eventTest(){
//这业务代码。。。。。。
System.out.println("eventTest~~~~~~~~~");
//驱动事件触发,创建我们自定义的事件对象
applicationContext.publishEvent(new MyEvent(applicationContext,"eventTest执行"));
}
}
@Autowired
private EventTestService eventTestService;
@Test
public void testEvent(){
eventTestService.eventTest();
}
spring实现事件监听注意这里的事件处理,spring在这里其实就是简单的去寻找监听者并执行onApplicationEvent方法而已。
我们进入原码看看:applicationContext.publishEvent(new MyEvent(applicationContext,“eventTest执行”));
applicationContext.publishEvent();