关于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.1 ApplicationListener简介
ApplicationContext事件机制是属于设计模式中的观察者设计模式,通过ApplicationEvent类和ApplicationListener接口实现事件处理.
当容器中有一个ApplicationListener对象, 当ApplicationContext发布ApplicationEvent事件时,ApplicationListener对象会被自动触发, 需要由程序来控制. 此外Spring中也内置了一下事件.
2.2 ApplicationListener案列
1 准备一个SpringBoot 环境
2 创建一个自定义的监听器
@ComponentpublicclassDemoApplicationListenerimplementsApplicationListener<ContextRefreshedEvent>{@OverridepublicvoidonApplicationEvent(ContextRefreshedEventevent){System.out.println(event);System.out.println("TestApplicationListener............................");}}
根据上述可知, ContextRefreshedEvent内置事件, 是ApplicationContext 被初始化或刷新时会发布, 即监听器可以收到回调信息.
3 启动项目,查看日志
3 关于ApplicationContext的说明
3.1 ApplicationContext的简介
从上述可知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.2 ApplicationContext的案列
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;}}