spring监听机制——观察者模式的应用
spring监听模式需要三个组件:
1. 事件,需要继承ApplicationEvent,即观察者模式中的"主题",可以看做一个普通的bean类,用于保存在事件监听器的业务逻辑中需要的一些字段;
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。2. 事件监听器,需要实现ApplicationListener<E extends ApplicationEvent>,即观察者模式中的"观察者",在主题发生变化时收到通知,并作出相应的更新,加泛型表示只监听某种类型的事件;
3. 事件发布器,需要实现ApplicationEventPublisherAware,获取spring底层组件ApplicationEventPublisher,并调用其方法发布事件,即"通知"观察者。
其中,事件监听器和事件发布器需要在springIOC容器中注册。
事件类
import org.springframework.context.ApplicationEvent; /** * spring监听机制中的"事件" * created on 2019-04-15 */ public class BusinessEvent extends ApplicationEvent { //事件的类型 private String type; /** * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) * 即事件是在哪个对象上发生的 */ public BusinessEvent(Object source, String type) { super(source); this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
事件监听器
import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * spring监听机制中"监听器" * created on 2019-04-15 */ @Component public class BusinessListener implements ApplicationListener<BusinessEvent> { /** * 监听到事件后做的处理 * @param event */ @Override public void onApplicationEvent(BusinessEvent event) { System.out.println("监听到事件:" + event.getType()); } }
事件发布器
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Component; /** * spring事件监听机制中的"事件发布器" * created on 2019-04-15 */ @Component public class BusinessPublisher implements ApplicationEventPublisherAware { //spring提供的事件发布组件 private ApplicationEventPublisher applicationEventPublisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } /** * 发布事件 */ public void publishEvent(BusinessEvent businessEvent) { System.out.println("发布事件:" + businessEvent.getType()); this.applicationEventPublisher.publishEvent(businessEvent); } }
容器配置类
/** * spring容器配置类 * 需要在容器中注册事件监听器、事件发布器 * created on 2019-04-15 */ @ComponentScan(basePackages = {"cn.monolog.bennett.observer.event.listener"}) public class BeanConfig { }
测试类
/** * 用于测试spring事件监听 * created on 2019-04-15 */ public class Test { public static void main(String[] args) { //创建springIOC容器 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class); //从容器中获取事件发布器实例 BusinessPublisher businessPublisher = applicationContext.getBean(BusinessPublisher.class); //创建事件 BusinessEvent businessEvent = new BusinessEvent(new Test(), BusinessType.ALLOT.getName()); //发布事件 businessPublisher.publishEvent(businessEvent); } }

更多精彩