阿里一面:Spring和SpringMvc父子容器你能说清楚吗 |
您所在的位置:网站首页 › springboot无法访问html › 阿里一面:Spring和SpringMvc父子容器你能说清楚吗 |
之前写了几篇关于SpringBoot的文章《面试高频题:springBoot自动装配的原理你能说出来吗》、《保姆级教程,手把手教你实现一个SpringBoot的starter》,这几天忽然有个读者问:能说一说Spring的父子容器吗?说实话这其实也是Spring八股文里面一个比较常见的问题。在个人印象里面Spring就是父容器,SpringMvc就是子容器,子容器能够访问父容器的内容,父容器不能访问子容器的东西。有点相似java里面的继承的味道,子类能够继承父类共有方法和变量,能够访问它们,父类不能够访问子类的方法和变量。在这里就会衍生出几个比较经典的问题:html 为何须要父子容器? 是否能够把全部类都经过Spring容器来管理?(Spring的applicationContext.xml中配置全局扫描) 是否能够把咱们所需的类都放入Spring-mvc子容器里面来管理(springmvc的spring-servlet.xml中配置全局扫描)? 同时经过两个容器同时来管理全部的类?若是可以把上面这四个问题能够说个因此然来,我的以为Spring的父子容器应该问题不大了。咱们能够看下官网提供的父子容器的图片![]() 要想很好的理解它们之间的关系,咱们就有必要先弄清楚Spring的启动流程。要弄清楚这个启动流程咱们就须要搭建一个SpringMvc项目,说句实话,用惯了SpringBooot开箱即用,忽然在回过头来搭建一个SpringMvc项目还真有点不习惯,一大堆的配置文件。(虽然也能够用注解来实现)具体怎么搭建SpringMvc项目这个就不介绍了,搭建好项目咱们运行起来能够看到控制台会输出以下日志: 咱们只须要Controller与咱们的Service中实现ApplicationContextAware接口,就能够得知对应的管理容器:在Service所属的父容器里面咱们能够看到父容器对应的对象是XmlWebApplicationContext@3972 咱们知道SpringServletContainerInitializer从 servlet 3.0 开始,Tomcat 启动时会自动加载实现了 ServletContainerInitializer 接口的类(须要在 META-INF/services 目录下新建配置文件)也称为 SPI(Service Provider Interface) 机制,SPI的应用仍是挺广的好比咱们的JDBC、还有Dubbo框架里面都有用到,若是还有不是很了解SPI机制的 能够去学习下。因此咱们的入口就是SpringServletContainerInitializer的onStartup方法,这也应该是web容器启动调用Spring相关的第一个方法。web 初始化SpringIoc若是实在找不到入口的话,咱们能够 根据控制台打印的日志,而后拿着日志进行反向查找这应该总能找到开始加载父容器的地方。启动的时候控制台应该会打印出“Root WebApplicationContext: initialization started” 咱们拿着这个日志就能定位到代码了面试 `public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {` `if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {` `throw new IllegalStateException(` `"Cannot initialize context because there is already a root application context present - " +` `"check whether you have multiple ContextLoader* definitions in your web.xml!");` `}` `servletContext.log("Initializing Spring root WebApplicationContext");` `Log logger = LogFactory.getLog(ContextLoader.class);` `if (logger.isInfoEnabled()) {` `logger.info("Root WebApplicationContext: initialization started");` `}` `long startTime = System.currentTimeMillis();` `try {` `// Store context in local instance variable, to guarantee that` `// it is available on ServletContext shutdown.` `if (this.context == null) {` `// 经过反射去建立context` `this.context = createWebApplicationContext(servletContext);` `}` `if (this.context instanceof ConfigurableWebApplicationContext) {` `ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;` `if (!cwac.isActive()) {` `// The context has not yet been refreshed -> provide services such as` `// setting the parent context, setting the application context id, etc` `if (cwac.getParent() == null) {` `// The context instance was injected without an explicit parent ->` `// determine parent for root web application context, if any.` `ApplicationContext parent = loadParentContext(servletContext);` `cwac.setParent(parent);` `}` `// IOC容器初始化` `configureAndRefreshWebApplicationContext(cwac, servletContext);` `}` `}` `servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);` `ClassLoader ccl = Thread.currentThread().getContextClassLoader();` `if (ccl == ContextLoader.class.getClassLoader()) {` `currentContext = this.context;` `}` `else if (ccl != null) {` `currentContextPerThread.put(ccl, this.context);` `}` `if (logger.isInfoEnabled()) {` `long elapsedTime = System.currentTimeMillis() - startTime;` `logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");` `}` `return this.context;` `}` `catch (RuntimeException | Error ex) {` `logger.error("Context initialization failed", ex);` `servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);` `throw ex;` `}` `}`这段代码就是建立父容器的地方。spring 初始化 Spring MVC接着咱们再来看看建立子容器的地方:在FrameworkServlet类 大概流程以下: 咱们知道了Sping父容器以及SpingMvc子容器的一个启动过程,以及每一个容器都分别干了什么事情如今再回过头来看看上述四个问题。架构 为何须要父子容器?父子容器的主要做用应该是划分框架边界。有点单一职责的味道。在J2EE三层架构中,在service层咱们通常使用spring框架来管理, 而在web层则有多种选择,如spring mvc、struts等。所以,一般对于web层咱们会使用单独的配置文件。例如在上面的案例中,一开始咱们使用spring-servlet.xml来配置web层,使用applicationContext.xml来配置service、dao层。若是如今咱们想把web层从spring mvc替换成struts,那么只须要将spring-servlet.xml替换成Struts的配置文件struts.xml便可,而applicationContext.xml不须要改变。 是否能够把全部类都经过Spring父容器来管理?(Spring的applicationContext.xml中配置全局扫描)全部的类都经过父容器来管理的配置就是以下: `` `` `` `` `` ``而后在SpringMvc的配置里面不配置扫描包路径。很显然这种方式是行不通的,这样会致使咱们请求接口的时候产生404。由于在解析@ReqestMapping注解的过程当中initHandlerMethods()函数只是对Spring MVC 容器中的bean进行处理的,并无去查找父容器的bean, 所以不会对父容器中含有@RequestMapping注解的函数进行处理,更不会生成相应的handler。因此当请求过来时找不处处理的handler,致使404。 站在巨人的肩膀上摘苹果: https://www.cnblogs.com/grasp... https://javajr.cn 往期精选*推荐👍 :Java高并发编程基础三大利器之CyclicBarrier* 推荐👍 :Java高并发编程基础三大利器之CountDownLatch 推荐👍 :Java高并发编程基础三大利器之Semaphore 推荐👍 :Java高并发编程基础之AQS 推荐👍 :可恶的爬虫直接把生产6台机器爬挂了! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |