设计模式——监听器模式(二)ApplicationContext

设计模式——监听器模式(二)ApplicationContext_第1张图片

 

/**
 *  事件
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Event {
    /**
     * 事件类型
     */
    private int eventType;

    /**
     * 消息体
     */
    private JSONObject msgJson;

}
package org.demo.spring.event;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 事件发布测试
 */
@Component
public class TestJob {

    @Autowired
    ApplicationContext applicationContext;


    @Scheduled(cron = "*/5 * * * * ?")
    public void cronJob() {
        Event event = new Event();
        event.setEventType(1);
        Map map = new HashMap() {
            {
                put("a", "123");
                put("b", "456");
            }
        };
        event.setMsgJson(new JSONObject().fluentPutAll(map));
        applicationContext.publishEvent(event);

        Event event2 = new Event();
        event2.setEventType(2);
        Map map2 = new HashMap() {
            {
                put("c", "1");
                put("d", "2");
            }
        };
        event2.setMsgJson(new JSONObject().fluentPutAll(map2));
        applicationContext.publishEvent(event2);
    }

}
package org.demo.spring.event;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 也可以实现ApplicationListener接口
 * 事件监听
 */
@Component
@Slf4j
public class IEventListener {

    @EventListener(condition = "#event.eventType==1")
    @Async
    public void eventF(Event event) {
        System.out.println("监听事件类型1:" + event.getMsgJson().toJSONString());
    }

    @EventListener(condition = "#event.eventType==2")
    @Async
    public void eventT(Event event) {
        System.out.println("监听事件类型2:" + event.getMsgJson().toJSONString());
    }

}

 相关文章:

ApplicationEvent事件机制源码分析

使用Observer实现观察者模式、EventListener实现监听器模式详解​​​​​​​

你可能感兴趣的:(设计模式,spring)