标签:title void 发布 gap text this data handle 业务
1.事件定义
import lombok.Data; import org.springframework.context.ApplicationEvent; /** * 事件定义,这里监听MsgMessage消息对象 */ @Data public class MsgApplicationEvent extends ApplicationEvent { private MsgMessage message; public MsgApplicationEvent(Object source,MsgMessage message) { super(source); this.message=message; } }
2.事件监听
import com.alibaba.fastjson.JSON; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; /** * 事件监听,处理事件 */ @Component public class HandleEnvent { @EventListener(MsgApplicationEvent.class) public void handeEnvent(MsgApplicationEvent event){ MsgMessage message= event.getMessage(); System.out.println("消息处理事件...:"+ JSON.toJSONString(message)); } }
3.发布事件
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; /** * 发布事件 */ @Service public class MsgPublishEvent { @Autowired ApplicationContext context; public void publishEvent(MsgMessage message){ context.publishEvent(new MsgApplicationEvent(new Object(),message)); } }
4.使用事件
事件使用结合具体业务注入即可
@Autowired private MsgPublishEvent msgPublishEvent; @GetMapping("/test") @ResponseBody public String test(){ MsgMessage message=new MsgMessage(); message.setTitle("hello"); message.setMessage("我是个消息提示哦!"); msgPublishEvent.publishEvent(message); return "success"; }
标签:title void 发布 gap text this data handle 业务
原文地址:https://www.cnblogs.com/huzi007/p/11676879.html