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、结果

相关推荐
没有bug.的程序员6 天前
Spring Boot 启动原理:从 @SpringBootApplication 到自动配置深度解析
java·spring boot·后端·python·springboot·application
源代码•宸9 天前
Golang原理剖析(context、context面试与分析)
开发语言·后端·算法·面试·golang·context·emptyctx
heartbeat..16 天前
Spring 全局上下文实现指南:单机→异步→分布式
java·分布式·spring·context
源代码•宸18 天前
Golang语法进阶(Context)
开发语言·后端·算法·golang·context·withvalue·withcancel
乐茵lin1 个月前
golang context底层设计探究
开发语言·后端·golang·大学生·设计·context·底层源码
乐茵lin1 个月前
golang中 Context的四大用法
开发语言·后端·学习·golang·编程·大学生·context
小小工匠1 个月前
LLM - 从 Prompt 到 Context:2026 Agent 时代的核心战场
prompt·agent·context
dingdingfish1 个月前
Oracle 《数据库 2 天开发人员指南》第10章:部署Oracle数据库应用程序
oracle·database·application·developer·deploy·guide
SuperHeroWu72 个月前
【HarmonyOS 6】为什么getContext 废弃,使用getHostContext说明
华为·harmonyos·context·上下文·getcontext·gethostcontext
Ice__Cai5 个月前
Flask 之上下文详解:从原理到实战
后端·python·flask·context·上下文