SpringBoot事件ApplicationEvent类

1.事件对象

@Data
@AllArgsConstructor
@NoArgsConstructor
public class EventObj implements Serializable {
    private String message;
    private int number;
}

2.自定义对象装配

@Data
public class CustomEventConfig extends ApplicationEvent {

    private EventObj eventObj;

    public CustomEventConfig(Object source, EventObj eventObj) {
        super(source);
        this.eventObj = eventObj;
    }
}

3.监听对象

@Slf4j
@Service
public class EventListenService {

    @Async
    @EventListener
    public void handleEvent(CustomEventConfig eventConfig){
        //监听 CustomEvent 事件
        String message = eventConfig.getEventObj().getMessage();
        int number = eventConfig.getEventObj().getNumber();
        log.info("---------------->收到第 {} 条信息,内容为:{}",number,message);

    }
}

5.推送监听的对象

@Service
public class DoEvenService {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void doEvent(){
        applicationEventPublisher.publishEvent(new CustomEventConfig(this, new EventObj("永恒花园和紫罗兰电影今天开播!", 124980)));
    }
}

6.调用方法

    @Autowired
    private DoEvenService doEvenService;

    @Test
    void contextLoads() {
        doEvenService.doEvent();
    }
发布了29 篇原创文章 · 获赞 0 · 访问量 377

猜你喜欢

转载自blog.csdn.net/qq_43399077/article/details/103870791
今日推荐