个人学习SpringBoot 之spring事件监听器
首先我们自己实现一个自己的事件监听器
package com.demo.springboot.bootstrap;
import com.demo.springboot.context.HelloWorldApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringEventListenerBootstrap {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.addApplicationListener(new HelloWorldApplicationListener());
context.refresh();
context.publishEvent(new ApplicationEvent("hello world") {
@Override
public Object getSource() {
return super.getSource();
}
@Override
public String toString() {
return super.toString();
}
});
context.close();
}
}
package com.demo.springboot.context;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.Ordered;
import java.lang.reflect.Method;
import java.util.stream.Stream;
public class HelloWorldApplicationListener implements ApplicationListener, Ordered {
@Override
public void onApplicationEvent(ApplicationEvent event) {
Method[] methods = event.getSource().getClass().getMethods();
// Stream.of(methods).forEach(method -> System.out.println(event.getSource().getClass().getName()+"#"+ method.getName()));
System.out.println("事件 =:"+event.getSource().getClass().getName());
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
启动测试类
package com.demo.springboot.bootstrap;
import com.demo.springboot.context.HelloWorldApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringEventListenerBootstrap {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.addApplicationListener(new HelloWorldApplicationListener());
context.refresh();
context.publishEvent(new ApplicationEvent("hello world") {
@Override
public Object getSource() {
return super.getSource();
}
@Override
public String toString() {
return super.toString();
}
});
context.close();
}
}
结果