Artigo Diretório
Prefácio
Ontem, olhei para o código-fonte da estrutura do Spring e descobri que ApplicationContext
essa parte do contêiner do Spring tem um seu próprio ApplicationEventPublisher
. Não é um push?
Aula de origem
//
// 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;
}
Configurar e usar
Já que vem com ele ApplicationEventPublisher
, como jogar?
- Escreva uma classe de aceitação de dados A classe de aceitação de
dados é usada principalmente para encapsular uma classe de aceitação de dados personalizada para encapsular a estrutura de informações de dados.
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;
}
}
Uma vez que o bean de registro da classe do listener precisa usar aApplicationEventPublisher
interface
//
// 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);
}
No publishEvent
método push data, deve haver uma classe de monitoramento que pode ser usada para receber informações relacionadas.
Escreva uma classe de ouvinte e registre-a no contêiner 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-notifique.xml:
<bean class="notify.NotifyListener" />
- Crie uma classe de teste
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);
}
}
Teste de corrida
É descoberto que depois que os dados são enviados para o contêiner, a classe de ouvinte correspondente no contêiner pode receber as informações de envio!
Precauções
1. Somente o contêiner ApplicationContext é permitido.
2. Pode haver muitos dados push, que devem ser usados de forma diferente na classe de monitoramento. tal como:
if(env instanceof EventNotify) {
·······
}