1. 程式人生 > >[SpringBoot] Spring的事件機制

[SpringBoot] Spring的事件機制

直接上程式碼:

一.定義事件

public class MyEvent extends ApplicationEvent {
    private String msg;
    
    public MyEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
    public String getMsg() { return msg;   }
}
PS:繼承ApplicationEvent 

二.定義監聽者

@Component
public class MyListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent myEvent) {
       //監聽後的邏輯,這裡簡單列印
        String msg = myEvent.getMsg();
        System.out.println("MyListener接收到了MyPublisher釋出的訊息:" + msg);
    }

}
PS:實現ApplicationListener介面,指定事件型別

三.定義釋出者

@Component
public class MyPublisher {
    @Autowired
    ApplicationContext context;

    public void published() {
        MyEvent event = new MyEvent(this, "釋出成功!");
        System.out.println("釋出event:" + event);
        context.publishEvent(event);
    }
}
PS:注入ApplicationContext ,通過ApplicationContext的publisEvent方法釋出事件; 

四.釋出測試

 
@SpringBootApplication
@RestController
public class SpringDefineConfigApplication {

    @Autowired
    MyPublisher myPublisher;

    public static void main(String[] args) {
        ApplicationContext applicationContext =
                SpringApplication.run(SpringDefineConfigApplication.class, args);
    }

    @GetMapping("/publish")
    public void publish(){
        myPublisher.published();
    }
}
PS:注入事件釋出者,只掉呼叫方法即可釋出事件
訪問/publish介面即可看到列印如下:
釋出event:com.intellif.mozping.event.MyEvent[
[email protected]
] MyListener接收到了MyPublisher釋出的訊息:釋出成功!

上述只是簡單的入門示例,可以自行完善滿足特定需求。