org.springframework.context.ApplicationContext发送消息

1、创建消息的实体类

复制代码
package com.demo;

/**
 * 监听的实体类
 *
 */
public class EventMessage {
    private String name;

    public EventMessage(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2、创建消息接收

复制代码
package com.demo;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class MessageEventListener {

    @EventListener(EventMessage.class)
    public void onApplicationEvent(EventMessage eventMessage) {
        System.out.println("监听器接收的消息:"+ eventMessage.getName());
    }
}

3、消息发送的controller

复制代码
package com.demo;


import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class MessageController {

    @Resource
    private ApplicationContext applicationContext;

    @RequestMapping("/messageListener")
    public String messageListener(){
        applicationContext.publishEvent(new EventMessage("你好帅"));
        return "success";
    }
}

4、使用postman触发

5、结果

相关推荐
乐茵lin1 天前
golang中 Context的四大用法
开发语言·后端·学习·golang·编程·大学生·context
小小工匠2 天前
LLM - 从 Prompt 到 Context:2026 Agent 时代的核心战场
prompt·agent·context
dingdingfish4 天前
Oracle 《数据库 2 天开发人员指南》第10章:部署Oracle数据库应用程序
oracle·database·application·developer·deploy·guide
SuperHeroWu71 个月前
【HarmonyOS 6】为什么getContext 废弃,使用getHostContext说明
华为·harmonyos·context·上下文·getcontext·gethostcontext
Ice__Cai4 个月前
Flask 之上下文详解:从原理到实战
后端·python·flask·context·上下文
有梦想的攻城狮4 个月前
spring中的ApplicationRunner接口详解
java·后端·spring·runner·application
草海桐8 个月前
Go语言中的Context
go·context
剑客狼心10 个月前
Android Studio:如何利用Application操作全局变量
android·android studio·application·全局变量
酒茶白开水1 年前
React五官方文档总结二状态管理
前端·react.js·前端框架·context·状态管理·usereducer
ezreal_pan1 年前
golang中的上下文
开发语言·后端·golang·context·上下文