1.自定义监听需要三个类
需要三个类:事件类、触发事件的类、监听事件的类
2.demo事件类
package com.example.demo.event;
import org.springframework.context.ApplicationEvent;
import com.alibaba.fastjson.JSONObject;
public class MyCustomEvent extends ApplicationEvent{
public MyCustomEvent(JSONObject jsonObject) {
super(jsonObject);
}
private static final long serialVersionUID = 5742580847294774499L;
}
3.demo触发事件类
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.event.MyCustomEvent;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class Application {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping("testPublishCustomEvent")
public String testPublishCustomEvent() {
//发布事件
JSONObject jsonObject = new JSONObject();
jsonObject.put("userName", "银真");
applicationContext.publishEvent(new MyCustomEvent(jsonObject));
return "test";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.demo事件监听类
package com.example.demo.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.event.MyCustomEvent;
@Component
public class MyCusttomEventListener implements ApplicationListener<MyCustomEvent>{
@Override
public void onApplicationEvent(MyCustomEvent event) {
JSONObject jsonObject = (JSONObject) event.getSource();
System.out.println(jsonObject);
}
}