ContextApplication Event : ApplicationContext « Spring « Java






ContextApplication Event

File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="publisher" class="EventPublisherDemo"/>
    <bean class="MessageEventListener"/>

</beans>


File: Main.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
  public static void main(String[] args) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");

    EventPublisherDemo pub = (EventPublisherDemo) ctx.getBean("publisher");
    pub.report("A");
    pub.report("B");
  }

}

class EventPublisherDemo implements ApplicationContextAware {

  private ApplicationContext ctx;

  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.ctx = applicationContext;

  }

  public void report(String message) {
    ctx.publishEvent(new MessageEvent(this, message));
  }

}

class MessageEvent extends ApplicationEvent {
  private String message;

  public MessageEvent(Object source, String message) {
    super(source);
    this.message = message;
  }

  public String getMessage() {
    return message;
  }
}

class MessageEventListener implements ApplicationListener {
  public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof MessageEvent) {
      MessageEvent messageEvent = (MessageEvent) event;
      System.out.println("Received " + messageEvent.getMessage());
    }
  }
}




           
       








Spring-ContextApplicationEvent.zip( 2,600 k)

Related examples in the same category

1.ResourceLoader Demo
2.Create ApplicationContext with ClassPathXmlApplicationContext
3.ApplicationContext Aware