见代码
什么是三层架构:controller(也叫web层)、service(也叫业务层)、dao(也叫dao层)
其它层: domain层(也叫实体)
'应用上下文'对象是通过new ClasspathXmlApplicationContext方式获取的,但是每次从容器中获得Bean时都要编 写new ClasspathXmlApplicationContext,这样的弊端是配置文件(applicationContext.xml)会加载多次,也就是 '应用上下文'对象会被创建多次。解决如下
在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建 '应用上下文'对象(ApplicationContext),在将其存储到最大的域(servletContext域)中, 这样就可以在任意位置从域中获得'应用上下文'对象(ApplicationContext)
见代码
上面用监听器获得应用上下文的写法,实际不用我们手写,因为Spring提供呢一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加 载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils就可获得应用上下文对象
我们只需要做两件事:
1、在web.xml中配置ContextLoaderListener监听器,即导入spring-web坐标
2、使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--配置监听器的全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name> <!--自定义名字,这里写什么名字,ContextLoaderListener的getInitParameter方法里面就写什么名字-->
<param-value>classpath:applicationContext.xml</param-value> <!--配置文件名称,一般说是applicationContext.xml-->
</context-param>
<!--配置spring给我们提供的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>