Spring 事件监听

参考:Spring事件监听流程分析【源码浅析】_private void processbean(final string beanname, fi-CSDN博客

一、简介

Spring早期通过实现ApplicationListener接口定义监听事件,Spring 4.2开始通过@EventListener注解实现监听事件

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);


    /**
     * Create a new {@code ApplicationListener} for the given payload consumer.
     * @param consumer the event payload consumer
     * @param <T> the type of the event payload
     * @return a corresponding {@code ApplicationListener} instance
     * @since 5.3
     * @see PayloadApplicationEvent
     */
    static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
       return event -> consumer.accept(event.getPayload());
    }


}

二、示例

(1)、自定义事件,相当于抽象观察者

/*
* 系统日志事件,观察者
* */
public class SysLogEvent extends ApplicationEvent {
    public SysLogEvent(SysLog sysLog){
        super(sysLog);
    }
}

(2)、自定义实现,相当于具体观察者

@Component
public class SysLogListener implements ApplicationListener<SysLogEvent> {
    private final static Logger logger = LoggerFactory.getLogger(SysLogListener.class);

    @Override
    public void onApplicationEvent(SysLogEvent event) {
        logger.info("收到调用日志消息:"+ JSON.toJSONString(event));
    }

    /*
    * spring 4.2版本用@EventListener注解
    * */
//    @EventListener(SysLogEvent.class)
    public void saveSysLog(SysLog event){
        logger.info("收到调用日志消息:"+ JSON.toJSON(event));
    }
}

(3)、发布订阅事件

@RestController
@RequestMapping("/event")
public class EventController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("public")
    public void event(){
       SysLog sysLog = new SysLog();
       sysLog.setLogId("1");
       sysLog.setCode("2");
       sysLog.setMessage("3");
       applicationContext.publishEvent(new SysLogEvent(sysLog));

    }
}

(4)、测试

相关推荐
潘多编程7 小时前
Java中的状态机实现:使用Spring State Machine管理复杂状态流转
java·开发语言·spring
_阿伟_7 小时前
SpringMVC
java·spring
杨半仙儿还未成仙儿13 小时前
Spring框架:Spring Core、Spring AOP、Spring MVC、Spring Boot、Spring Cloud等组件的基本原理及使用
spring boot·spring·mvc
攸攸太上17 小时前
Spring Gateway学习
java·后端·学习·spring·微服务·gateway
无理 Java21 小时前
【技术详解】SpringMVC框架全面解析:从入门到精通(SpringMVC)
java·后端·spring·面试·mvc·框架·springmvc
gobeyye21 小时前
spring loC&DI 详解
java·spring·rpc
java6666688881 天前
Java中的对象生命周期管理:从Spring Bean到JVM对象的深度解析
java·jvm·spring
王维诗里的代码i1 天前
Redis基础二(spring整合redis)
java·数据库·redis·spring
椰椰椰耶1 天前
【Spring】@RequestMapping、@RestController和Postman
java·后端·spring·mvc
大道归简1 天前
2.点位管理开发(续)及设计思路——帝可得后台管理系统
java·开发语言·spring boot·spring·前端框架