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