Spring学习_Spring开发web项目_拆分web配置文件_servlet容器与IOC的桥梁

Spring开发web项目

因为java中有唯一的入口main()函数,所以java程序中初始化IOC容器可以直接:

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

web程序没有统一的入口,每次使用都要初始化IOC特别浪费性能,那么,怎么简化呢?
思路:通过监听器当我们每次启动服务器时初始化IOC容器。
Spring开发web项目:
你能想到的别人都想到了,直接调用前辈们给的方法就行。
下载Spring-web.jar:https://mvnrepository.com/artifact/org.springframework/spring-web/5.1.3.RELEASE
web.xml文件:

<?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>

在src目录下新建applicationContext.xml文件即可。applicationContext.xml即为IOC容器。

拆分web配置文件

1、根据功能拆分
2、根据三层结构拆分
拆容易,怎么合并呢?
在这里插入图片描述

servlet容器与IOC的桥梁

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

愿你心如花木,向阳而生

猜你喜欢

转载自blog.csdn.net/nbcsdn/article/details/99644506