Spring learning_Spring development web project_Split web configuration file_Servlet container and IOC bridge

Spring development web project

Because there is the only entry main() function in java, the IOC container can be initialized directly in the java program:

//初始化spring容器,加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

There is no unified entry point for web programs. It is a waste of performance to initialize IOC every time it is used. So, how to simplify it?
Idea: Through the listener, we initialize the IOC container every time we start the server.
Spring development web project:
Everyone you can think of has thought of it, just call the method given by the predecessors directly.
Download Spring-web.jar : https://mvnrepository.com/artifact/org.springframework/spring-web/5.1.3.RELEASE
web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--指定IOC容器,contextConfigLocation名固定-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <!--配置监听器,初始化IOC容器-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

Create a new applicationContext.xml file in the src directory. applicationContext.xml is the IOC container.

Split web configuration file

1. Split according to function 2. Split
according to three-layer structure
Easy to split , how to merge?
Insert picture description here

The bridge between servlet container and IOC

//获取IOC容器到servlet容器
    @Override
    public void init() throws ServletException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        context.getbean("对象");
    }

May your heart be like flowers and trees

Guess you like

Origin blog.csdn.net/nbcsdn/article/details/99644506