@Service
public class MessageEventListenerServiceImpl<T> implements MessageEventListenerService<T> {
private Map<Integer, Consumer<T>> RULE;
@PostConstruct
public void initRule() {
RULE = new HashMap<>(4);
RULE.put(1, this::businessOne);
RULE.put(2, this::businessTwo);
}
@EventListener
public void events(SendNotificationEventVO<T> event) {
RULE.get(event.getType()).accept(event.getBusinessKey());
}
@Override
public void businessOne(T t) {
User user = (User) t;
System.out.println(t);
}
@Override
public void businessTwo(T t) {
System.out.println(t);
}
}
public class SendNotificationEventVO<T> extends ApplicationEvent {
private T businessKey;
private Integer type;
public SendNotificationEventVO(Object source, T businessKey, Integer type) {
super(source);
this.businessKey = businessKey;
this.type = type;
}
public T getBusinessKey() {
return businessKey;
}
public void setBusinessKey(T businessKey) {
this.businessKey = businessKey;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
@Test
public void sendMeg(){
SendNotificationEventVO<User> userSendNotificationEventVO =new SendNotificationEventVO<>(this,new User("wpf","26"),1);
applicationContext.publishEvent(userSendNotificationEventVO);
applicationContext.publishEvent(new SendNotificationEventVO<String>(this,"方法二",2));
}