笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

Spring Boot 监听器处理

Posted on 2024-05-31 14:44  草妖  阅读(2)  评论(0)    收藏  举报
EventListenModel.java
package com.namejr.bean;

/**
 * 监听模型
 * */
public class EventListenModel {
    public Integer codeStatus;
    public String errInfo;
}
EventListenSource.java
package com.namejr.base;

import com.namejr.bean.EventListenModel;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class EventListenSource{
    @EventListener
    public void handelEventListener(EventListenModel model){
        System.out.println("做监听器要处理的事情:"+model.codeStatus+","+model.errInfo);
    }
}
PublicController,java
package com.namejr.controller;

import com.namejr.bean.EventListenModel;
import com.namejr.serviceImpl.PublicServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/public")
@Validated
public class PublicController {
    @Autowired
    private PublicServiceImpl pServiceImpl;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @RequestMapping(value = "/getServerTime", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public String getServerTime() {
        return DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
    }

    @RequestMapping(value = "/runEventListen", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public void runEventListen() {
        EventListenModel tempEventListenModel =new EventListenModel();
        tempEventListenModel.errInfo="测试处理";
        tempEventListenModel.codeStatus=1;
        applicationEventPublisher.publishEvent(tempEventListenModel);
    }
}

访问127.0.0.1:8080/api/public/runEventListen输出:

。。。。
2024-05-31 14:43:38.760  INFO -- [nio-8080-exec-2] o.a.c.c.C.[.[.[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-05-31 14:43:38.761  INFO -- [nio-8080-exec-2] s.w.s.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2024-05-31 14:43:38.761  INFO -- [nio-8080-exec-2] s.w.s.DispatcherServlet : Completed initialization in 0 ms
做监听器要处理的事情:1,测试处理