Implements ApplicationListener : ApplicationContext « Spring « Java Tutorial






File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

  <bean id="heartbeatTask" class="HeartbeatTask"/>
  
  <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
    <property name="timerTask"><ref local="heartbeatTask"/></property>
    <property name="period"><value>1000</value></property>
  </bean>

  <bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
    <property name="scheduledTimerTasks">
      <list>
        <ref local="scheduledTask"/>
      </list>
    </property>
  </bean>
  
  <bean id="heartbeatForwarder" class="HeartbeatForwarder"/>

</beans>

File: Main.java

import java.util.TimerTask;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
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");
    Thread.sleep(30 * 1000);

  }
}

class HeartbeatTask extends TimerTask implements ApplicationEventPublisherAware {

  private ApplicationEventPublisher eventPublisher;

  public void run() {
    HeartbeatEvent event = new HeartbeatEvent(this);
    eventPublisher.publishEvent(event);
  }

  public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }
}

class HeartbeatForwarder implements ApplicationListener {
  public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof HeartbeatEvent) {
      System.out.println("Received heartbeat event: " + event.getTimestamp());
    }
  }
}

class HeartbeatEvent extends ApplicationEvent {
  public HeartbeatEvent(Object source) {
    super(source);
  }
}
  Download:  Spring-ImplementsApplicationListener.zip( 2,895 k)








28.2.ApplicationContext
28.2.1.ApplicationContext component scan
28.2.2.Component Filter Assignable
28.2.3.Search By Base Package
28.2.4.Implements ApplicationListener
28.2.5.Implements ApplicationEvent Publisher Aware
28.2.6.Filter By Annotation
28.2.7.ApplicationContext Aware
28.2.8.ApplicationContext And BeanFactory PostProcessor