Processing logic:
Custom events (including required data bodies) ---> custom listeners (you can limit the events that need to be monitored through generics, of course, you can also not involve) ---> publish events to IOC ---> in The process of completing the actual business in the listener.
1. Custom events.
Inherit ApplicationEvent
package com.shanxilgong.linxi.listener; import org.springframework.context.ApplicationEvent; import java.util.HashMap; import java.util.Map; /** * custom events */ public class MyApplicationEvent extends ApplicationEvent { public MyApplicationEvent(Object source) { super(source); } private Map<String,String> data = new HashMap<String,String>(); public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } }
2. Simulate the southbound acquisition task
2.1 The ioc container in spring boot
ConfigurableApplicationContext application = SpringApplication.run(SmalprocesssApplication.class, args);
Start the scheduled task:
Timing task: Line 34, build an event object. Line 37 publishes events to the IOC container.
1 package com.shanxilgong.linxi.listener; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.context.ConfigurableApplicationContext; 5 import org.springframework.stereotype.Component; 6 7 import java. util.HashMap; 8 import java.util.Map; 9 import java.util.TimerTask; 10 11 12 /** * 13 * This scheduled task is used to simulate the southbound periodic collection task and publish collection result events. 14 */ 15 16 @Component 17 public class MyTimerTask extends TimerTask 18 { 19 20 @Autowired 21 private ConfigurableApplicationContext configurableApplicationContext; 22 23 public MyTimerTask(){ 24 25 } 26 27 @Override 28 public void run() 29 { 30 Map map = new HashMap(); 31 map.put("name","zhangsan"); 32 map.put("age","20"); 33 34 MyApplicationEvent event = new MyApplicationEvent( new Object()); 35 event.setData(map); 36 // spring's ioc container, publish events 37 configurableApplicationContext.publishEvent(event); 38 } 39 }
3. Custom listener
Implement ApplicationListener, and add the event generics that need to be monitored, such as line 14. (Of course, you can also not add listener event generics)
1 package com.shanxilgong.linxi.listener; 2 3 import org.springframework.context.ApplicationEvent; 4 import org.springframework.context.ApplicationListener; 5 import org.springframework.stereotype.Component; 6 7 import java.lang.reflect. Method; 8 9 /** 10 * Custom listener 11 * 1. You can specify which type of event to listen to through generics 12 */ 13 14 public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> 15 { 16 @Override 17 public void onApplicationEvent(MyApplicationEvent event) 18 { 19 System.out.println("The captured data is: "+ event.getData()); 20 } 21 }