Spring试错笔记(一)

Spring对C3P0数据库连接池注入时出现的问题

Spring中使用C3P0数据源需要导入2个——3个jar包
Spring试错笔记(一)
​ mchange-commons-java-0.2.19.jar这是c3p0数据库连接池的辅助包,如果没有这个包系统启动时会报classnotfoundexception,这是更新c3p0-0.9.2版本后分离出来的包,0.9.1的时候还是只是一个包。

如果没有导入这个辅助包,配置bean时,不报错,但是获取容器实例化bean时会报错;
xml配置c3p0:

  <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="user" value="root"/>
        <property name="password" value=""/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/study"/>
    </bean>

测试代码:

    @Test
    public void testDataSource() throws SQLException {
        ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("ioc3.xml");
        DataSource dataSource = ac.getBean("datasource",DataSource.class);
        System.out.println(dataSource);
    }

报错信息:

警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasource' defined in class path resource [ioc3.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mchange.v2.c3p0.ComboPooledDataSource]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector
    //翻译大概意思就是:创建名为'datasource'的bean时出错,该bean在类路径资源[ioc3.xml]中定义:实例化bean失败,为找到默认构造函数
    //但是ComboPooledDataSource是有无参构造的,所以可能无法找到准确的错误原因

导入辅助包后正常获取到DataSource:

结果:

信息: Initializing c3p0-0.9.5.5 [built 11-December-2019 22:07:46 -0800; debug? true; trace: 10]
com.mchange.v2.c3p0.ComboPooledDataSource[ identityToken -> 1b61iobahze2bpj1a5zcgw|7fc229ab, dataSourceName -> 1b61iobahze2bpj1a5zcgw|7fc229ab ]

Process finished with exit code 0
上一篇:SSM学习----Spring配置数据源


下一篇:SpringBoot--实现Mybatis的多数据源切换和动态数据源切换