标签:curl cut lis com nal 容器 xmla eth sys
8.1.4 属性占位符配置器
PropertyPlaceholderConfigurer 是一个容器后处理器,负责读取Properties属性文件里的属性值,并将这些属性值设置成Spring配置文件的数据。
通过使用PropertyPlaceholderConfigurer后处理器,可以将Spring配置文件中的部分数据放在属性文件中设置。
XML :
<?xml version="1.0" encoding="UTF-8"?> <!-- Spring 配置文件的根元素,使用Spring-beans-4.0.xsd语义约束 --> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>dbconn.properties</value> <!-- 如果有多个属性文件,依次在下面列出来 --> <!-- <value>wawa.properties</value> --> </list> </property> </bean> <!-- 对于采用基于XML Schema的配置文件而言,如果导入了context:命名空间,则可采用如下方式来配置该属性占位符 --> <!-- <context:property-placeholder location="classpath:wawa.properties"/> --> <!-- 定义数据源Bean,使用C3P0数据源实现 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- Spring容器将从PropertyPlaceholderConfigurer指定的属性文件中搜索这些key对应的value,并为该Bean的属性值设置这些value值 --> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> </beans>
Properties :
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=system
Class : Main
package edu.pri.lime._8_1_4.main; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("app_8_1_4.xml"); DataSource ds = null; PreparedStatement pstmt = null; Connection conn = null; try { ds = ctx.getBean("dataSource",DataSource.class); conn = ds.getConnection(); pstmt = conn.prepareStatement("insert into news_inf values(null,?,?)"); pstmt.setString(1, "lime"); pstmt.setString(2, "Oracle"); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(pstmt != null) try { pstmt.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(conn != null) try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
啦啦啦
8 -- 深入使用Spring -- 1...4 属性占位符配置器
标签:curl cut lis com nal 容器 xmla eth sys
原文地址:http://www.cnblogs.com/ClassNotFoundException/p/6384084.html