事件监听实现代码解耦

  1. 定义要发布的事件对象,需要继承ApplicationEvent类
  2. 事件发布者,需要注入ApplicationEventPublisher对象
  3. 事件监听者对象,需要实现ApplicationListener接口
package com.cockpit.web.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Author: tangchuanzhu
 * @Date: 2025/7/21 13:25
 */
@Configuration
public class EventListenerTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventListenerTest.class);
        context.getBean(MyService.class).doPublish();
        context.close();
    }

    /**
     * 需要发布事件的对象
     */
    static class MyEvent extends ApplicationEvent {

        public MyEvent(Object source) {
            super(source);
        }
    }

    /**
     * 事件发布者对象
     */
    @Component
    static class MyService {

        private static final Logger log = LoggerFactory.getLogger(MyService.class);

        @Autowired
        private ApplicationEventPublisher publisher;

        public void doPublish() {
            log.info("主线业务");
            publisher.publishEvent(new MyEvent("MyService.doPublish()"));
        }
    }

    /**
     * 事件监听者对象
     */
    @Component
    static class SmsApplicationListener implements ApplicationListener<MyEvent> {

        private static final Logger log = LoggerFactory.getLogger(SmsApplicationListener.class);

        @Override
        public void onApplicationEvent(MyEvent event) {
            log.info("发送短信。。。。");
        }
    }

    /**
     * 事件监听者对象
     */
    @Component
    static class EmailApplicationListener implements ApplicationListener<MyEvent> {

        private static final Logger log = LoggerFactory.getLogger(SmsApplicationListener.class);

        @Override
        public void onApplicationEvent(MyEvent event) {
            log.info("发送邮件。。。。");
        }
    }
}
posted @ 2025-07-21 14:05  紫川先生  阅读(10)  评论(0)    收藏  举报