Spring通過bean配置連線資料庫的引數
阿新 • • 發佈:2019-02-08
1.C3P0
C3P0是一個開源的JDBC連線池,它實現了資料來源和JNDI繫結,支援JDBC3規範和JDBC2的標準擴充套件。
C3P0常用包下載地址:
連結:https://pan.baidu.com/s/18RSPWJ8NDgeOiXzY-WJlxg 密碼:42x3
下面是基本的實現步驟:
建立一個配置檔案db.proerties:
jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/bookstorejdbc.initialPoolSize=5
jdbc.maxPoolSize=10
宣告一個applicationContext.xml檔案:
<context:property-placeholder location="classpath:db.properties"/> <!-- 配置C3P0資料來源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value=""></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean>
使用該資料庫配置:
private ApplicationContext ctx=null;
ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
2.Spring自帶的JDBC
需匯入檔案:spring-jdbc-5.0.8.RELEASE.jar
db.protities檔案:
url=jdbc:mysql://localhost:3306/test
driverClassName=com.mysql.jdbc.Driver
username=root
password=
bean配置:
<context:property-placeholder location="db.protities"/>
<bean id="dataSource" name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${driverClassName}" p:url="${url}" p:username="root" p:password="" />
測試:
ApplicationContext ctx=new ClassPathXmlApplicationContext("beansql.xml");
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());