Chapter 10, Integration of Spring and Spring MVC

Keywords: Spring xml encoding Junit

Article directory

1. Integration of Spring and Spring MVC

(1) Does Spring need to integrate Spring MVC?

(2) Do you need to add Spring's IOC container?

(3) Do you need to configure Content Loader Listener to start the Spring IOC container in the web.xml file?

Need: Usually, other frameworks like data sources, transactions, and integration are placed in Spring configuration files (rather than in Spring MVC configuration files).

In fact, there are also Service and Dao in the IOC container corresponding to the Spring configuration file.

No: They are all in the Spring MVC configuration file. They can also be divided into multiple Spring configuration files, and then make

Importing other configuration files with import nodes

2. Spring Integration Spring MVC - Solution Configuration Listener

(1) How to create Spring container objects?

  • Non-WEB environment: In main method or junit test method, it is created by new Classpath Xml Application Context ().

  • WEB environment: Based on request-response model.

    • Timing of creation: Tomcat server startup.
    • Listener: ServletContext Session Request
    • ServletContext: Context objects are created at server startup, destroyed at server shutdown, and created only once, with global scope.
    • Implementing ideas: By listening for the creation of ServletContext objects by the listener, when listening for the corresponding creation events, you can create in the event handling method.
    • Spring's container object. Then the created Spring container object is saved in the ServletContext object and shared with each component.
  • Spring provides listeners: ContextLoaderListener

  • Case: Simulated monitoring process

(2) Spring listener configuration

<!-- Configuration startup Spring IOC Container Listener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

(3) Create Spring beans configuration file: beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
<!-- Setting up packages for scanning components -->
<context:component-scan base-package="com.xxj.springmvc"/>
 
<!-- Configuring data sources, Integrating other frameworks, Affairs, etc.. -->
 
</beans>

(4) Spring MVC configuration file: springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
<!-- Setting up packages for scanning components -->
<context:component-scan base-package="com.xxj.springmvc"/> 
<!-- Configuration view parser -->
<bean id="internalResourceViewResolver"
   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
 
<mvc:default-servlet-handler/> 
<mvc:annotation-driven/> 
</beans>

Add constructors to HelloWorldHandler and UserService classes, start the server, and view the implementation of the constructor.

Problem: If Spring's IOC container and Spring MVC's IOC container scan packages have overlapping parts, some bean s will be created twice.

Solve:

There is no overlap between the packages scanned by Spring's IOC container and those scanned by Spring's MVC's IOC container.

Use exclude-filter and include-filter subnodes to specify only scanned annotations

springmvc.xml


<context:component-scan base-package="com.xxj.springmvc" use-default-filters="false">
<context:include-filter type="annotation"
           expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
           expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

beans.xml


<context:component-scan base-package="com.xxj.springmvc">
<context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
        expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- Configuring data sources, Integrating other frameworks, Affairs, etc.. -->

3. The relationship between Spring IOC container and Spring MVC IOC container

Beans in Spring MVC's IOC container can be used to reference bean s in Spring IOC container.

Back? On the contrary, No. Beans in Spring IOC containers cannot be referenced by bean s in Spring MVC IOC containers.

(1) Referring to Business Layer Bean s in Spring MVC Configuration Files

(2) Father-child relationship can be set between multiple Spring IOC containers to achieve good decoupling.

(3) Spring MVC WEB Layer Container can be used as a sub-container of "Business Layer" Spring Container:

That is, the WEB layer container can refer to the Bean of the business layer container, while the business layer container can not access the Bean of the WEB layer container.

Container objects created by Spring MVC can be viewed at 460 lines of DispatherServlet with breakpoints
Container objects created by Spring can be viewed in line 296 of ContextLoader with breakpoints

4) Get Spring's container object in Handler's method:

  • servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

  • WebApplicationContextUtils.getWebApplicationContext(servletContext)

4. Handwritten Spring listener

Train of thought:

1. Create Spring container objects during server startup

2. Place Spring container objects in the application scope

3. Container objects can be retrieved from the application scope in servlet s

4. Obtain bean objects managed in containers through container objects

public class MyListener implements ServletContextListener {

    public MyListener() {
    }

    public void contextDestroyed(ServletContextEvent arg0)  { 
    }

    public void contextInitialized(ServletContextEvent sce)  { 
     //First step
    	//When the server is started, a ServletContext object is created, and if it is created, a ServletContext object is created.
    	//Get the ServletContext object
    	ServletContext servletContext = sce.getServletContext();
    	
    	//Then the current method will be executed, creating a Spring container in the method
    	//ApplicationContext context = new ClassPathXmlApplicationContext("spring-mvc.xml");
    	String contextConfigLocation = servletContext.getInitParameter("myContextConfigLocation");
    	ApplicationContext context = new ClassPathXmlApplicationContext(contextConfigLocation);
        
        
      //The second step
    	//Place Spring container in servletContext(application)
    	servletContext.setAttribute("context", context);
    	
    }
	
}

public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MyServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//The third step
		//Get application
		ServletContext servletContext = request.getServletContext();
		//Getting Spring containers from application
		//ApplicationContext context = (ApplicationContext) servletContext.getAttribute("context");
		ApplicationContext context 
			= (ApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
     //The fourth step
		//Get the bean s managed by the container through the Spring container
		Person person = context.getBean("person", Person.class);
		response.getWriter().write(person.toString());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

Posted by TweetyPie on Tue, 10 Sep 2019 04:52:42 -0700