Spring中ApplicationListener和ApplicationContext的使用

如题所述

第1个回答  2024-09-05

关于Spring的源码相关功能

1引入ApplicationContext

ApplicationContext是Spring的一个核心接口,允许容器通过应用程序上下文环境创建,获取,管理bean.

publicinterfaceApplicationContextextendsEnvironmentCapable,ListableBeanFactory,HierarchicalBeanFactory,MessageSource,ApplicationEventPublisher,ResourcePatternResolver{/***Returntheuniqueidofthisapplicationcontext.*@returntheuniqueidofthecontext,or{@codenull}ifnone*/@NullableStringgetId();/***Returnanameforthedeployedapplicationthatthiscontextbelongsto.*@returnanameforthedeployedapplication,ortheemptyStringbydefault*/StringgetApplicationName();/***Returnafriendlynameforthiscontext.*@returnadisplaynameforthiscontext(never{@codenull})*/StringgetDisplayName();/***Returnthetimestampwhenthiscontextwasfirstloaded.*@returnthetimestamp(ms)whenthiscontextwasfirstloaded*/longgetStartupDate();/***Returntheparentcontext,or{@codenull}ifthereisnoparent*andthisistherootofthecontexthierarchy.*@returntheparentcontext,or{@codenull}ifthereisnoparent*/@NullableApplicationContextgetParent();AutowireCapableBeanFactorygetAutowireCapableBeanFactory()throwsIllegalStateException;}

ApplicationContext提供的功能:

访问应用程序组件的Bean工厂方法.从org.springframework.beans.factory.ListableBeanFactory继承而来.

publicinterfaceListableBeanFactoryextendsBeanFactory{......}

通用方式加载文件资源的能力.从org.springframework.core.io.support.ResourcePatternResolver继承而来.

packageorg.springframework.core.io.support;importjava.io.IOException;importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;publicinterfaceResourcePatternResolverextendsResourceLoader{StringCLASSPATH_ALL_URL_PREFIX="classpath*:";Resource[]getResources(Stringvar1)throwsIOException;}

向注册监听器发布事件的能力.从org.springframework.context.ApplicationEventPublisher继承而来.

@FunctionalInterfacepublicinterfaceApplicationEventPublisher{defaultvoidpublishEvent(ApplicationEventevent){publishEvent((Object)event);}voidpublishEvent(Objectevent);}

解析消息的能力,支持国际化.从org.springframework.context.MessageSource继承而来.

publicinterfaceMessageSource{@NullableStringgetMessage(Stringcode,@NullableObject[]args,@NullableStringdefaultMessage,Localelocale);StringgetMessage(Stringcode,@NullableObject[]args,Localelocale)throwsNoSuchMessageException;StringgetMessage(MessageSourceResolvableresolvable,Localelocale)throwsNoSuchMessageException;}

从父上下文继承,后代上下文中的定义总是优先级.单个父上下文可以被整个web应用程序使用,而每个servlet都有自己独立于任何其他servlet的子上下文.

2关于ApplicationListener的说明2.1ApplicationListener简介

ApplicationContext事件机制是属于设计模式中的观察者设计模式,通过ApplicationEvent类和ApplicationListener接口实现事件处理.

当容器中有一个ApplicationListener对象,当ApplicationContext发布ApplicationEvent事件时,ApplicationListener对象会被自动触发,需要由程序来控制.此外Spring中也内置了一下事件.

内置事件说明ContextRefreshedEventApplicationContext被初始化或刷新时,该事件被发布。这也可以在ConfigurableApplicationContext接口中使用refresh()方法来发生。此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有SingletonBean被预实例化,ApplicationContext容器已就绪可用ContextStartedEventConfigurableApplicationContext(ApplicationContext子接口)接口中的start()方法启动ApplicationContext时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序ContextStoppedEventConfigurableApplicationContext接口中的stop()停止ApplicationContext时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作ContextClosedEventConfigurableApplicationContext接口中的close()方法关闭ApplicationContext时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启RequestHandledEvent是web-specific事件,告诉所有beanHTTP请求已经被服务处理。只能应用于使用DispatcherServlet的Web应用。在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件2.2ApplicationListener案列1准备一个SpringBoot环境2创建一个自定义的监听器@ComponentpublicclassDemoApplicationListenerimplementsApplicationListener<ContextRefreshedEvent>{@OverridepublicvoidonApplicationEvent(ContextRefreshedEventevent){System.out.println(event);System.out.println("TestApplicationListener............................");}}

根据上述可知,ContextRefreshedEvent内置事件,是ApplicationContext被初始化或刷新时会发布,即监听器可以收到回调信息.

3启动项目,查看日志

3关于ApplicationContext的说明3.1ApplicationContext的简介

从上述可知ApplicationContext具有发布事件的能力,是从ApplicationEventPublisher接口继承来的.而Spring中的事件使用,需要继承ApplicationEvent类或ApplicationContextEvent抽象类,抽象类中只有一个构造函数,且带有一个Object类型的参数作为事件源,且该事件源不能为null,因此我们需要在自己的构造函数中执行super(Object)。

publicclassEventObjectimplementsjava.io.Serializable{privatestaticfinallongserialVersionUID=5516075349620653480L;/***TheobjectonwhichtheEventinitiallyoccurred.*/protectedtransientObjectsource;/***ConstructsaprototypicalEvent.**@paramsourceTheobjectonwhichtheEventinitiallyoccurred.*@exceptionIllegalArgumentExceptionifsourceisnull.*/publicEventObject(Objectsource){if(source==null)thrownewIllegalArgumentException("nullsource");this.source=source;}....}3.2ApplicationContext的案列3.2.1准备一个SpringBoot环境@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);testEvent();}//@Bean//publicFeignInterceptorfeignInterceptor(){//returnnewFeignInterceptor();//}//测试事件publicstaticvoidtestEvent(){ApplicationContextcontext=newAnnotationConfigApplicationContext(EventConfig.class);DemoEventdemoEvent=newDemoEvent(context,"小明",20);context.publishEvent(demoEvent);}}3.2.2创建一个自定义的监听器@ComponentpublicclassDemo2ApplicationListenerimplementsApplicationListener<ApplicationEvent>{@OverridepublicvoidonApplicationEvent(ApplicationEventevent){//针对自定义事件做处理if(eventinstanceofDemoEvent){System.out.println(event);DemoEventdemoEvent=(DemoEvent)event;System.out.println("姓名:"+demoEvent.getUsername()+",年龄:"+demoEvent.getAge());System.out.println("自定义DemoEvent事件............................");}}}3.2.3创建一个自定义的事件publicclassDemoEventextendsApplicationEvent{privateStringusername;privateintage;/***CreateanewApplicationEvent.**@paramsourcetheobjectonwhichtheeventinitiallyoccurred(never{@codenull})*/publicDemoEvent(Objectsource,Stringusername,intage){super(source);this.username=username;this.age=age;}publicStringgetUsername(){returnusername;}publicvoidsetUsername(Stringusername){this.username=username;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}}3.2.4启动项目,查看日志

logo设计

创造品牌价值

¥500元起

APP开发

量身定制,源码交付

¥2000元起

商标注册

一个好品牌从商标开始

¥1480元起

公司注册

注册公司全程代办

¥0元起

    官方电话官方服务
      官方网站八戒财税知识产权八戒服务商企业需求数字市场
相似回答
大家正在搜