Spring ApplicationEvent 事件(观察者设计模式)
一. 发布ApplicationEvent(目标)
1)自定义TestEvent
public class TestEvent extends ApplicationEvent { public TestEvent(Object source) { super(source); } }
2)发布
① ApplicationContext发布
// 发布event并传参args SpringContextUtils.getApplicationContext().publishEvent(new TestEvent("args"));
② 实现ApplicationEventPublisherAware接口
@Service public class DynamicRouteService implements ApplicationEventPublisherAware { @Autowired private MyInMemoryRouteDefinitionRepository repository; /** * 发布事件 */ private ApplicationEventPublisher publisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } /** * 删除路由 * * @param id * @return */ public synchronized void delete(String id) { try { repository.delete(Mono.just(id)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); } catch (Exception e) { log.warn(e.getMessage(), e); } }
}
二. 事件监听ApplicationListener(观察者)
1)自定义事件监听器
@Component public class TestListener1 implements ApplicationListener<TestEvent> { @Override public void onApplicationEvent(TestEvent event) { Object obj = event.getSource(); // 处理业务 System.out.println("==========listerer1"+obj); } }
@Component public class TestListener2 implements ApplicationListener<TestEvent> { @Override public void onApplicationEvent(TestEvent event) { Object obj = event.getSource(); // 处理业务 System.out.println("==========listerer2"+obj); } }

浙公网安备 33010602011771号