平常的子类继承父类通过extends关键字来实现,那么Spring父容器与SpringMVC子容器是如何体现出父子关系的呢?容器指的是一个类吗?Spring容器是哪个类,SpringMVC容器又是哪个类?
2 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
所谓容器,就是上下文,在这同一个上下文里,大家可以共享一些东西。在Spring应用启动时,会先读取web.xml文件,调用ContextLoaderListener创建Spring容器,也就是你说的父容器。org.springframework.web.context.ContextLoaderListener Listener创建完之后,开始创建Servlet:SpringMVC org.springframework.web.servlet.DispatcherServlet 这时候这个DispatcherServlet开始试图创建SpringMVC的ApplicationContext,它先找刚才由上面那个ContextLoaderListener创建的Spring的ApplicationContext,找到后,把Spring的ApplicationContext作为参数传给DispatcherServlet的ApplicationContext的setParent方法,这样SpringMVC的容器就变成了Spring容器的儿子。因为在SpringMVC这个子容器创建的时候指定了它的Spring父容器,所以儿子能找到父亲,所以SpringMVC这个子容器里的Bean可以调用父容器的服务,而父容器不知道有这个儿子的存在(一个不负责任的父亲),父容器里的Bean不能调用子容器里的服务。
手掌心
TA贡献1942条经验 获得超3个赞
想必Servlet的关系就不必多说了,直接上代码吧HttpServletBean继承了HttpServlet,init方法如下@Overridepublicfinalvoidinit()throwsServletException{//Letsubclassesdowhateverinitializationtheylike.initServletBean();}看看子类FrameworkServlet#initServletBean方法@OverrideprotectedfinalvoidinitServletBean()throwsServletException{this.webApplicationContext=initWebApplicationContext();initFrameworkServlet();}看看initWebApplicationContextprotectedWebApplicationContextinitWebApplicationContext(){WebApplicationContextrootContext=WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContextwac=null;if(this.webApplicationContext!=null){wac=this.webApplicationContext;if(wacinstanceofConfigurableWebApplicationContext){ConfigurableWebApplicationContextcwac=(ConfigurableWebApplicationContext)wac;if(!cwac.isActive()){//Thecontexthasnotyetbeenrefreshed->provideservicessuchas//settingtheparentcontext,settingtheapplicationcontextid,etcif(cwac.getParent()==null){//Thecontextinstancewasinjectedwithoutanexplicitparent->set//therootapplicationcontext(ifany;maybenull)astheparent,看到没有,如果有就设置rootApplicationContext,cwac.setParent(rootContext);}configureAndRefreshWebApplicationContext(cwac);}}}if(wac==null){//Nocontextinstancewasinjectedatconstructiontime->seeifone//hasbeenregisteredintheservletcontext.Ifoneexists,itisassumed//thattheparentcontext(ifany)hasalreadybeensetandthatthe//userhasperformedanyinitializationsuchassettingthecontextidwac=findWebApplicationContext();}if(wac==null){//Nocontextinstanceisdefinedforthisservlet->createalocalonewac=createWebApplicationContext(rootContext);}if(!this.refreshEventReceived){//EitherthecontextisnotaConfigurableApplicationContextwithrefresh//supportorthecontextinjectedatconstructiontimehadalreadybeen//refreshed->triggerinitialonRefreshmanuallyhere.看到这里就不多说了,初始化beanFactoryonRefresh(wac);}if(this.publishContext){StringattrName=getServletContextAttributeName();getServletContext().setAttribute(attrName,wac);}returnwac;}结束,就是辣么简单
添加回答
举报
0/150
提交
取消