| 1.创建自定义Event,使其继承ApplicationEvent package cn.edu.tju.event;
import org.springframework.context.ApplicationEvent;
    public class MyEvent extends ApplicationEvent {
        private String msg;
        public String getMsg() {
            return msg;
        }
        public void setMsg(String msg) {
            this.msg = msg;
        }
        public MyEvent(Object source, String msg){
        super(source);
        this.msg=msg;
    }
}
 2.定义Event Listener来监听上述event的发生: package cn.edu.tju.listener;
import cn.edu.tju.event.MyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class MyEventListener {
    @EventListener
    public void gotMyEvent(MyEvent myEvent){
        System.out.println("event message is:"+myEvent.getMsg());
    }
}
 3.触发自定义Event, package cn.edu.tju.controller;
import cn.edu.tju.event.MyEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EventController {
    @Autowired
    private ApplicationContext applicationContext;
    @RequestMapping("/createEvent")
    public String createEvent(String str){
        MyEvent myEvent=new MyEvent(this,"test event");
        applicationContext.publishEvent(myEvent);
        return "MyEvent triggered......";
    }
}
 4.调用/createEvent接口,运行效果如下:
  5.同时,也可以在启动spring boot程序时,手动注册Event Listener.
 首先定义类来实现泛型接口ApplicationListener
 package cn.edu.tju.listener;
import cn.edu.tju.event.MyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class YourEventListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("test: "+event.getMsg());
    }
}
 然后在启动程序时添加上述Listener: package cn.edu.tju;
import cn.edu.tju.listener.MyEventListener;
import cn.edu.tju.listener.YourEventListener;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Start {
    public static void main(String[] args) {
        //SpringApplication.run(Start.class,args);
        SpringApplication springApplication=new SpringApplication(Start.class);
        //springApplication.setLazyInitialization(false);
        //springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.addListeners(new YourEventListener());
        springApplication.run(args);
    }
}
 |