applicationContext 的事件機制是觀察者設計模式,經過ApplicationEvent 類,和ApplicationListener 接口,能夠實現ApplicationContext 的事件處理,若是容器中有一個ApplicationListener Bean每當ApplicationContext發佈ApplicationEvent時,ApplicationListener Bean將自動被觸發:java
Spring 內置事件:spring
例1設計模式
監聽當spring容器的啓動app
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class SpringRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> { private final Logger logger = LoggerFactory.getLogger(SpringRefreshedEventListener.class); @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { logger.debug("spring 容器已經就緒。。。。"); } }
例2:ide
發佈事件:this
//自定義事件 import org.springframework.context.ApplicationEvent; public class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } } //發佈自定義事件 import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class MyEventPublisher implements ApplicationContextAware { private ApplicationContext applicationContext; public void publish(){ MyEvent myEvent = new MyEvent(null); applicationContext.publishEvent(myEvent); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
例3debug
發佈事件:設計
Publisher類實現 org.springframework.context.ApplicationEventPublisherAware 接口code
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Component; @Component public class MyEventPublisherII implements ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; public void publish(){ MyEvent myEvent = new MyEvent(null); applicationEventPublisher.publishEvent(myEvent); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }