Parent child container relationship of Spring and Spring MVC
General configuration code
<!-- listeners -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!--servlet -->
<servlet>
<servlet-name>myWebName</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config-mvc.xml</param-value>
</init-param>
<!-- 1 Or a number greater than 0: initialize the servlete,Call it init Method-->
<!-- 0 Or not configured, first access servlet Initialize the servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myWebName</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
spring-config.xml
<context:component-scan base-package="com.lzc.home" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
spring-config-mvc.xml
<context:component-scan base-package="com.lzc.home.controller">
</context:component-scan>
In the above configuration, after the creation of the Spring container (context), when initializing the Spring MVC container, the previously initialized Spring container will be set as its parent container. If the Spring parent container is not initialized in the project, Spring MVC will also initialize a default parent container.
Spring container - parent container
Spring MVC container - child container
Parent child container relationship:
1. The child container can access the resources (bean s) of the parent container
Example: Controller can inject Service
2. The parent container cannot access the resource (bean) of the child container
Note: in the above configuration, the packages scanned by the Spring MVC child container can only be limited to the controller package. If the packages scanned by the Spring container and the Spring MVC container are all configured, all the custom beans will be created in the child container and the parent container. When the service and DAO are loaded in the subclass container, the control layer will use the bean loaded by the subclass container to execute. But there is no transaction and other functions in the service (there is no configuration of Spring framework), just ordinary beans, so there will be unpredictable problems when using it.