@Test public void beanPostProcessorPublishesEvents() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("postProcessor", new RootBeanDefinition(EventPublishingBeanPostProcessor.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertEquals(4, listener.getEventCount()); context.close(); }
Map<?, ?> retrieverCache = TestUtils.getPropertyValue(multicaster, "retrieverCache", Map.class); ctx.publishEvent(new TestApplicationEvent1()); ctx.publishEvent(event2); assertEquals(3, retrieverCache.size()); for (Map.Entry<?, ?> entry : retrieverCache.entrySet()) { ctx.publishEvent(new ApplicationEvent("Some event") {
@Test public void testPayloadEvents() { GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); QueueChannel channel = new QueueChannel(); ApplicationEventListeningMessageProducer listenerMessageProducer = new ApplicationEventListeningMessageProducer(); listenerMessageProducer.setOutputChannel(channel); listenerMessageProducer.setEventTypes(String.class); beanFactory.registerSingleton("testListenerMessageProducer", listenerMessageProducer); ctx.refresh(); ctx.publishEvent("foo"); Message<?> receive = channel.receive(10000); assertNotNull(receive); assertEquals("foo", receive.getPayload()); ctx.close(); }
public static void main(String[] args) { // 创建 Spring 应用上下文 GenericApplicationContext GenericApplicationContext context = new GenericApplicationContext(); // 注册 ApplicationListener<MyApplicationEvent> 实现 MyApplicationListener context.registerBean(MyApplicationListener.class); // registerBean 方法从 Spring 5 引入 // 初始化上下文 context.refresh(); // 发布自定义事件 MyApplicationEvent context.publishEvent(new MyApplicationEvent("Hello World")); // 关闭上下文 context.close(); // 再次发布事件 context.publishEvent(new MyApplicationEvent("Hello World Again")); }