13. Using Spring container under Spring web project

Keywords: xml Spring Java JavaEE

QQ group: Java data sharing group 59174518

Suppose we create the ApplicationContext container according to the method we learned

   @Test
    public void fun1() {
        // 1. First, create the container,
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        // 2. Get the user object from the container
        User user = (User) applicationContext.getBean("user");
        // 3. Print the obtained user object
        System.out.println(user);
    }

Every time a method is called, a container will be created. If multiple objects are called, it will be taken as too many containers and poor performance of the whole project

How to ensure that there is only one ApplicationContext container in the project?

  • Spring has provided a listener to implement this function
  • This listener enables the ApplicationContext container to be started as the project starts and destroyed as the project is destroyed
  • First of all, the package: spring-web-4.2.4.RELEASE.jar
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Spring-01</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
<!-- Specify listener -->
<!-- This will make Spring The container can be started as the project starts ,Destruction of project -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
<!-- adopt context-param Specified loading Spring configuration file-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:ApplicationContext.xml</param-value>
	</context-param>
</web-app>

How to get the container after configuration?

  • We think that the container is created in the listener after it is created, and the event source can be obtained in the listener. So we can get the spring container object
  • It's the Application domain, so as long as you get it in the Application domain. The Application domain stores the yes key value pairs. So I need to know the key value
  • So spinning encapsulates the key value pair in a tool method, which is "WebApplicationContextUtils.getWebApplicationContext(sc)"

Posted by mrinfin1ty on Thu, 26 Dec 2019 09:29:19 -0800