Spring實戰之屬性佔位符配置器用法示例
阿新 • • 發佈:2020-01-07
本文例項講述了Spring實戰之屬性佔位符配置器用法。分享給大家供大家參考,具體如下:
一 配置檔案
<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- PropertyPlaceholderConfigurer是一個容器後處理器,它會讀取 屬性檔案資訊,並將這些資訊設定成Spring配置檔案的資料。 --> <bean class= "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>dbconn.properties</value> <!-- 如果有多個屬性檔案,依次在下面列出來 --> <!--value>wawa.properties</value--> </list> </property> </bean> <!-- 定義資料來源Bean,使用C3P0資料來源實現 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}"/> </beans>
二 資料庫配置屬性
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.username=root jdbc.password=32147
三 測試類
package lee; import javax.sql.DataSource; import java.sql.*; import org.springframework.context.*; import org.springframework.context.support.*; public class BeanTest { public static void main(String[] args)throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); DataSource ds = (DataSource)ctx.getBean("dataSource"); Connection conn = ds.getConnection(); PreparedStatement pstmt = conn.prepareStatement( "insert into news_inf value(null,?,?)"); pstmt.setString(1,"瘋狂Java講義1"); pstmt.setString(2,"Struts 2權威指南2"); pstmt.executeUpdate(); pstmt.close(); conn.close(); } }
四 測試結果
更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》
希望本文所述對大家java程式設計有所幫助。