1.我们需要定义一个事件(MyTestEvent ) , 需要继承 Spring 的 ApplicationEvent 类

public class MyTestEvent extends ApplicationEvent {

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

2.注册事件

@SpringBootApplication
public class NmpJainSipApplication implements ApplicationRunner {

    @Autowired
    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(NmpJainSipApplication.class, args);
    }

    //@EventListener监听自定义事件
    //对应的方法传入的参数 , 是哪个类就是监听的哪个自定义事件
    @EventListener
    public void testEvent(MyTestEvent test){
        System.out.println("我触发了...............");
    }

    //该方法是SpringIOC容器加载完后执行,需要实现ApplicationRunner接口 ,为了演示方便 ,我们在这里注册自定义事件
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //注册自定义事件 , 就是new一下自定义事件
        applicationContext.publishEvent(new MyTestEvent(new Object()));
    }
}

3.还可以在自定义事件中 , 添加属性

public class MyTestEvent extends ApplicationEvent {
    //属性1
    private RedisHelper redisHelper;
    //属性2
    private KafkaTemplate kafkaTemplate;

    public MyTestEvent(Object source,RedisHelper redisHelper, KafkaTemplate kafkaTemplate) {
        super(source);
        this.redisHelper = redisHelper;
        this.kafkaTemplate = kafkaTemplate;
    }

    public RedisHelper getRedisHelper() {
        return redisHelper;
    }

    public KafkaTemplate getKafkaTemplate() {
        return kafkaTemplate;
    }
}

4.注册事件

@SpringBootApplication
public class NmpJainSipApplication implements ApplicationRunner {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    public static void main(String[] args) {
        SpringApplication.run(NmpJainSipApplication.class, args);
    }

    //@EventListener监听自定义事件
    //对应的方法传入的参数 , 是哪个类就是监听的那个自定义事件
    @EventListener
    public void testEvent(MyTestEvent test){
        System.out.println("我触发了...............");
        KafkaTemplate kafkaTemplate = test.getKafkaTemplate();
        RedisHelper redisHelper = test.getRedisHelper();
        System.out.println(kafkaTemplate+"==========="+redisHelper);
    }

    //该方法是SpringIOC容器加载完后执行,需要实现ApplicationRunner接口 ,为了演示方便 ,我们在这里注册自定义事件
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //注册自定义事件 , 就是new一下自定义事件
        applicationContext.publishEvent(new MyTestEvent(new Object(),redisHelper,kafkaTemplate));
    }
}
02-13 10:04