最近在项目中遇到一些奇葩的问题:在页面刷新多次后就报错了,报错原因是数据库的连接数太多。最后的原因分析如下:

1、在每次拿bean的时候都重新的new了一个新的容器对象。

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

这句话即使重新new一次AppliactionContext对象,然而在每次new的时候都会重新的去解读beans.xml中的配置信息,包括重新建立一个新的数据源连接对象。

所以这样在每次拿bean容器的时候很快就new出了很多的连接,当这些连接数足够多的时候就报错了:Too Many Connections


2、解决方法:使用IOC思想,直接配置bean.xml,将需要的bean容器对象直接注入到所要用到的bean中,例如:

<bean id="departmentDao" class="cn.dao.departmentDao.impl.DepartmentDaoImpl"/>		
	<bean id="departmentService" class="cn.service.deparmentservice.impl.DepartmentServiceImpl">
	    <property name="departmentDao" ref="departmentDao"></property>
	</bean>	
	<bean id="departmentAction" class="cn.action.department.DepartmentAction">
	    <property name="departmentService" ref="departmentService"></property>
	    <property name="positionService" ref="positionService"></property>	    
	</bean>
这样的好处是:使用了Spring为我们提供的IOC思想,减少了实例化对象的过程。


3、直接new bean容器和注入的区别

经过本人观察,直接new ApplicationContext对象时的耗时是比较长的,多次new对象则耗费更多的时间,这体现在页面刷新更慢,而是用注入则只是Spring帮我们初始化了一次,使得后面的操作不需要重新new ApplicationContext对象,这样就减少了响应时间。



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐