1.业务类注册一个监听者,发布事件
@Service
@Slf4j
public class Testimpl implements ITestService {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public test(){
BatteryTestCommandInfo batteryTestCommandInfo = new BatteryTestCommandInfo();
batteryTestCommandInfo.setDeviceId("xxxx");
batteryTestCommandInfo.setBatteryName("xxxx");
batteryTestCommandInfo.setCode("xxxx");
applicationEventPublisher.publishEvent(new BatteryTestDataUploadEvent(batteryTestCommandInfo));
}
}
2.事件
public class BatteryTestDataUploadEvent extends ApplicationEvent {
public BatteryTestDataUploadEvent(BatteryTestCommandInfo batteryTestCommandInfo) {
super(batteryTestCommandInfo);
}
public Long getDeviceId() {
BatteryTestCommandInfo batteryTestCommandInfo = (BatteryTestCommandInfo) getSource();
return batteryTestCommandInfo.getDeviceId();
}
public String getBatteryName() {
BatteryTestCommandInfo batteryTestCommandInfo = (BatteryTestCommandInfo) getSource();
return batteryTestCommandInfo.getBatteryName();
}
public Integer getCode() {
BatteryTestCommandInfo batteryTestCommandInfo = (BatteryTestCommandInfo) getSource();
return batteryTestCommandInfo.getCode();
}
}
3.监听器
@Component
@Slf4j
public class BatteryTestDataEventListener {
//处理A事件
@EventListener
public void handleReceiveBatterTestDataUpload(BatteryTestDataUploadEvent batterTestDataUploadEvent) {
Long deviceId = batterTestDataUploadEvent.getDeviceId();
String batteryName = batterTestDataUploadEvent.getBatteryName();
Integer code = batterTestDataUploadEvent.getCode();
}
//处理B事件
@EventListener
public void handleIssueBatteryTestCommandEvent(IssueBatteryTestCommandEvent issueBatteryTestCommandEvent) {
//do something
}
}