什么是Spring事件? Spring事件是Spring框架中的核心模块之一,可以通过事件来实现2个动作之间的连接。举个例子,我去银行取钱,我先输入银行账号、再输入银行密码,密码正确我们才能取到钱。如果把这2个动作看做一个事件,可以理解为验证账号、验证密码,两个动作都通过了,才进行下一步。 验证密码的动作是比较耗时的,可以通过事件来进行异步验证,用方法替代为checkUserName(Stringusername),然后再checkPassWord(Stringpwd); 写一下伪代码: publicbooleanlogin(Stringusername,Stringpwd){ checkUserName(username); 用户名存在后,再进行下一步。 checkPassWord(username,pwd); returntrue; }事件的用法 上述的动作换成事件,验证完用户名后就要验证密码,这相当于是一个连贯的动作。 publicbooleanlogin(Stringusername,Stringpwd){ checkUserName(username); publishCheckPwdEvent(username,pwd); } 接着需要在checkUserName后发布一个事件,使用ApplicationContext接口publishEvent()方法进行发布事件。 publicclassEventPublish{ privatefinalApplicationContextapplicationContext; Autowired publicEventPublish(ApplicationContextapplicationContext){ this。applicationContextapplicationContext; } publicvoidpublishEvent(Stringmessage){ System。out。println(发布事件。。。); applicationContext。publishEvent(newEvent(this,message)); } } 然后我们可以自定一个监听器。实现ApplicationListener接口,重写该接口下的onApplicationContext()方法。 publicclassEventListenerimplementsApplicationListener{ Override publicvoidonApplicationEvent(Eventevent){ Stringmsgevent。getEventMessage(); System。out。println(监听器一收到消息:msg); 解析event对象,拿到usernam和password后进行下一步验证。 valiadate(event。getUserName(),event。getPwd()); } } 如果需要异步,可以在方法上添加Async注解总结 上述简单介绍了Spring时间的用法,需要记住一个重要的接口ApplicationListener和applicationContext接口的publishEvent()方法,前者用来监听,后者用来发布。