spring配置第三方的Bean(資料庫連線池)
阿新 • • 發佈:2022-05-28
mysql驅動和druid連線池依賴配置:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> </dependencies>
maven會自動匯入對應的包:
xml配置Bean:
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="username" value="root"></property> <property name="password" value="123456"></property> <property name="url" value="jdbc:mysql://localhost:3306/db1"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean>
測試程式碼:
/** * 資料庫連線池 */ @Test public void fun7(){ System.out.println("begin!"); DruidDataSource dataSource = ioc.getBean("dataSource", DruidDataSource.class); System.out.println(dataSource); }
執行結果:
begin! { CreateTime:"2022-05-28 19:57:28", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } 程序已結束,退出程式碼為 0
建立資原始檔:
內容:
mysql.username=root
mysql.password=123456
mysql.url=jdbc:mysql://localhost:3306/db1
mysql.driverClassName=com.mysql.jdbc.Driver
xml配置:
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="username" value="${mysql.username}"></property> <property name="password" value="747699"></property> <property name="url" value="jdbc:mysql://localhost:3306/db1"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean> <context:property-placeholder location="db.properties"></context:property-placeholder>
再次執行:
begin! { CreateTime:"2022-05-28 20:09:48", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } 程序已結束,退出程式碼為 0
沒有問題!