前言
昨天看Spring框架源码部分,发现Spring容器中的ApplicationContext
这个容器部分,居然自带有一个ApplicationEventPublisher
,这然道不是推送么?
源码类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;
public interface ApplicationContext extends EnvironmentCapable,
ListableBeanFactory, HierarchicalBeanFactory, MessageSource,
ApplicationEventPublisher, ResourcePatternResolver {
@Nullable
String getId();
String getApplicationName();
String getDisplayName();
long getStartupDate();
@Nullable
ApplicationContext getParent();
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
配置和使用
既然自带ApplicationEventPublisher
,如何玩呢?
- 编写数据接受类
数据接受类,主要是封装一个自定义的数据接受类,用于封装数据信息结构。
package notify;
import org.springframework.context.ApplicationEvent;
public class EventNotify extends ApplicationEvent {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public EventNotify(Object source) {
super(source);
}
public EventNotify(Object source, String msg) {
super(source);
this.msg = msg;
}
}
- 监听类注册bean
既然需要使用到ApplicationEventPublisher
接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context;
@FunctionalInterface
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
this.publishEvent((Object)event);
}
void publishEvent(Object var1);
}
中的publishEvent
方法,推送数据,那么一定有一个可以用来接受相关信息的监听类。
编写监听类,并注册至Spring容器中:
package notify;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class NotifyListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent env) {
System.out.println(env);
EventNotify eventNotify = (EventNotify) env;
System.out.println("--->"+eventNotify.getMsg());
}
}
spring-notify.xml :
<bean class="notify.NotifyListener" />
- 建立测试类
package notify;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) throws InterruptedException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-notify.xml");
applicationContext.publishEvent(new EventNotify("xiangjiao","666666"));
TimeUnit.SECONDS.sleep(5);
}
}
运行测试
发现向容器中推送数据后,容器中对应的监听类可以收到推送信息!
注意事项
1、只允许ApplicationContext容器。
2、推送数据可能很多,在监听类中应该区别使用。比如:
if(env instanceof EventNotify) {
·······
}