Spring整合c3p0使用@PropertySource注解遇到的问题
最近在学习Spring时,遇到了一个解决了但是还不清楚原理的问题,这里做一下记录。
在Spring整合c3p0时,我们打算使用@PropertySource,将连接数据库的相关信息封装到dbConfig.properties文件中,一开始创建的dbConfig.properties文件如下:
1 2 3 4 driver = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8 username = root password = 123456
相关配置类(子配置类)代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package config;import com.mchange.v2.c3p0.ComboPooledDataSource;import org.apache.commons.dbutils.QueryRunner;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import org.springframework.context.annotation.Scope;import javax.sql.DataSource;import java.beans.PropertyVetoException;@Configuration @PropertySource ("classpath:dbConfig.properties" )public class DBConfig { @Value ("${driver}" ) private String driver; @Value ("${url}" ) private String url; @Value ("${username}" ) private String username; @Value ("${password}" ) private String password; @Bean (name = "queryRunner" ) public QueryRunner createQueryRunner (DataSource dataSource) { return new QueryRunner(dataSource); } @Bean (name = "dataSource" ) public DataSource createDataSource () throws PropertyVetoException { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(driver); dataSource.setJdbcUrl(url); dataSource.setUser(username); dataSource.setPassword(password); return dataSource; } }
运行测试类的findAll方法后确一直报错:com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
后来将dbConfig.properties修改如下:
1 2 3 4 jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8 jdbc.username = root jdbc.password = 123456
对应的相关配置类(子配置类)修改代码如下:
1 2 3 4 5 6 7 8 @Value ("${jdbc.driver}" )private String driver;@Value ("${jdbc.url}" )private String url;@Value ("${jdbc.username}" )private String username;@Value ("${jdbc.password}" )private String password;
结果就可以正常运行了:
具体的底层原因还没弄清楚,这里简单记录一下。如果你知道具体原因还烦请在评论区告诉我一下,谢谢啦!