进行spring自定义事件步骤:
1、继承ApplicationEvent自定义事件;
2、实现接口ApplicationListener定义事件监听器;
3、使用ApplicationContext来发布事件;
一、继承ApplicationEvent自定义事件
代码如下:
/**
* 自定义事件
* @author lyq
*/
public class DemoEvent extends ApplicationEvent {
private String msg;
public DemoEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
二、实现接口ApplicationListener定义事件监听器
代码如下:
/**
* 定义事件监听器
* 实现ApplicationListener接口,指定监听的事件类型
* onApplicationEvent对消息进行接受处理
* @author lyq
*/
@Component
public class DemoEventListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent demoEvent) {
String msg = demoEvent.getMsg();
System.out.println("事件监听器监听到事件消息DemoEvent,消息内容为: "+msg);
}
}
三、使用ApplicationContext来发布事件
代码如下:
/**
* 事件发布类
* 使用ApplicationContext来发布事件
* @author lyq
*/
@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String msg) {
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
四、在main方法中new DemoPublisher进行发布(其中定义了EventConfig配置文件,用来自动扫描对应的包注入成bean对象)
main方法类代码如下:
/**
* @author lyq
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher demoPublisher = applicationContext.getBean(DemoPublisher.class);
demoPublisher.publish("我来发布消息");
applicationContext.close();
}
}
配置类代码如下:
/**
* @author lyq
*/
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.event")
public class EventConfig {
}