观察者模式之Spring: event和listener
2021-05-13 06:28
标签:ubi listen img div webapp beans springmvc lse yml pom.xml main 观察者模式之Spring: event和listener 标签:ubi listen img div webapp beans springmvc lse yml 原文地址:https://www.cnblogs.com/smileblogs/p/13131914.htmlpackage cn.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationMain {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
}
package cn.it.event;
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
System.out.println("my Event");
}
public void print(){
System.out.println("hello spring event[MyEvent]");
}
}
package cn.it.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class MyListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof MyEvent){
System.out.println("into My Listener");
MyEvent myEvent=(MyEvent)event;
myEvent.print();
}
}
}
package cn.it.event;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
@Component
public class MyPubisher implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
public void publishEvent(ApplicationEvent event){
System.out.println("into My Publisher‘s method");
applicationContext.publishEvent(event);
}
}
package cn.it.event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyTest {
@Resource
MyPubisher myPublisher;
@Test
public void test(){
MyEvent myEvent = new MyEvent("1");
this.myPublisher.publishEvent(myEvent);
}
}
文章标题:观察者模式之Spring: event和listener
文章链接:http://soscw.com/essay/85017.html