Spring Boot 监听值变化并触发事件
在 Spring Boot 中,可以使用监听器来监听某个值的改变,从而触发事件。具体实现方式如下:
- 定义一个监听器类,实现
ApplicationListener接口,重写onApplicationEvent方法。
@Component
public class ValueChangeListener implements ApplicationListener<ValueChangeEvent> {
@Override
public void onApplicationEvent(ValueChangeEvent event) {
// 获取变化的值
String oldValue = event.getOldValue();
String newValue = event.getNewValue();
// 处理变化事件
System.out.println('Value changed from ' + oldValue + ' to ' + newValue);
}
}
- 定义一个事件类,用于封装变化的值。
public class ValueChangeEvent extends ApplicationEvent {
private String oldValue;
private String newValue;
public ValueChangeEvent(Object source, String oldValue, String newValue) {
super(source);
this.oldValue = oldValue;
this.newValue = newValue;
}
public String getOldValue() {
return oldValue;
}
public String getNewValue() {
return newValue;
}
}
- 在需要监听的地方,使用
ApplicationEventPublisher发布事件。
@Autowired
private ApplicationEventPublisher eventPublisher;
public void setValue(String value) {
// 获取旧值
String oldValue = this.value;
// 设置新值
this.value = value;
// 发布事件
eventPublisher.publishEvent(new ValueChangeEvent(this, oldValue, value));
}
这样,当某个值被改变时,就会触发 ValueChangeListener 中的 onApplicationEvent 方法,从而处理变化事件。
原文地址: https://www.cveoy.top/t/topic/nH2k 著作权归作者所有。请勿转载和采集!