Spring应用程序事件
一、定义应用程序事件
MessageEvent.java
package com.airkisser;
import org.springframework.context.ApplicationEvent;
public class MessageEvent extends ApplicationEvent {
public MessageEvent(Object source) {
super(source);
}
}
二、发布应用程序事件
package com.airkisser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class EventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Scheduled(fixedDelay = 1000L)//每秒执行一次
public void publish() {
// 发布事件
eventPublisher.publishEvent(new MessageEvent(new Date()));
}
}
三、订阅应用程序事件
package com.airkisser;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
@Service
public class EventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof MessageEvent) {
System.out.println(event.getSource());
}
}
}
四、结果
Mon Mar 13 11:04:52 CST 2017
Mon Mar 13 11:04:53 CST 2017
Mon Mar 13 11:04:54 CST 2017
Mon Mar 13 11:04:55 CST 2017
Mon Mar 13 11:04:56 CST 2017
Mon Mar 13 11:04:57 CST 2017
Mon Mar 13 11:04:58 CST 2017