參考:Spring事件監聽流程分析【源碼淺析】_private void processbean(final string beanname, fi-CSDN博客
一、簡介
? ? Spring早期通過實現ApplicationListener接口定義監聽事件,Spring 4.2開始通過@EventListener注解實現監聽事件
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {/*** Handle an application event.* @param event the event to respond to*/void onApplicationEvent(E event);/*** Create a new {@code ApplicationListener} for the given payload consumer.* @param consumer the event payload consumer* @param <T> the type of the event payload* @return a corresponding {@code ApplicationListener} instance* @since 5.3* @see PayloadApplicationEvent*/static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {return event -> consumer.accept(event.getPayload());}}
二、示例
? ? (1)、自定義事件,相當于抽象觀察者? ???
/*
* 系統日志事件,觀察者
* */
public class SysLogEvent extends ApplicationEvent {public SysLogEvent(SysLog sysLog){super(sysLog);}
}
?? ?(2)、自定義實現,相當于具體觀察者
@Component
public class SysLogListener implements ApplicationListener<SysLogEvent> {private final static Logger logger = LoggerFactory.getLogger(SysLogListener.class);@Overridepublic void onApplicationEvent(SysLogEvent event) {logger.info("收到調用日志消息:"+ JSON.toJSONString(event));}/** spring 4.2版本用@EventListener注解* */
// @EventListener(SysLogEvent.class)public void saveSysLog(SysLog event){logger.info("收到調用日志消息:"+ JSON.toJSON(event));}
}
?? ?(3)、發布訂閱事件
@RestController
@RequestMapping("/event")
public class EventController {@Autowiredprivate ApplicationContext applicationContext;@RequestMapping("public")public void event(){SysLog sysLog = new SysLog();sysLog.setLogId("1");sysLog.setCode("2");sysLog.setMessage("3");applicationContext.publishEvent(new SysLogEvent(sysLog));}
}
??(4)、測試