监听器工作原理
为了避免每次客户端访问服务器都创建spring容器对象,使得每次都生成bean对象造成内存浪费,可以使用监听器让spring只创建一次,并加入服务器的全局作用域 ServletContext中.
监听器是一个特殊的类,实现了HttpSessionListener接口,用于监听Tomcat容器的生命周期
监听器在服务器开启时,执行contextInitialized
初始化方法,创建spring容器并加入到全局作用域;当容器关闭或重启时,执行contextDestroyed
结束方法.
在servlet中调用spring容器对象的固定代码:
//使用框架中的方法获取对象
ServletContext sc = getServletContext();
ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
注意事项
1.要在pom文件中加入依赖,可以使用监听器
<!--使用监听器,加入依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2.在不使用监听器时,spring对mybatis配置文件的读取可以是
<!-- 声明的是mybatis中提供的SqlSessionFactoryBean类,由此创建SqlSessionFactory的对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,载入数据库连接池-->
<property name="dataSource" ref="myDataSource"/>
<!-- 载入映射配置文件-->
<property name="configLocation" value="mybatis.xml"/>
</bean>
其中读取mybatis配置文件的value="mybatis.xml"
可以不加classpath
而当变为监听器创建bean对象时,必须加classpath,否则会抛异常,无法读取mybatis.xml
文件
<property name="configLocation" value="classpath:mybatis.xml"/>