过程:定义一个event和一个listener,再在event publisher class中通过ApplicationEvent.publishEvent(java.lang.Object event)方法发布事件。
1、Event
package com.event;
import org.springframework.context.ApplicationEvent;
public class DemoEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private String msg;
public DemoEvent(Object source, String msg) {
// ApplicationEvent is contract, so must pick up another constructor(the one of EventObject) to initialize instance.
super(source);
this.msg = msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
2、Listener
package com.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
// This annotation must exist, otherwise container can instantiate the bean to listen message
@Component
public class DemoListener implements ApplicationListener<DemoEvent>{
@Override
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMsg();
System.out.println("I'm a application event listener, I've received a message from event publisher: " + msg);
}
}
3、Event Publisher(ie source)
package com.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String msg) {
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
4、Configutaion
package com.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.event")
public class EventConfig {
}
5、Test
package com.event;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Bootrap {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher publisher = context.getBean(DemoPublisher.class);
publisher.publish("Hello, application event listener.");
context.close();
}
}