spring配置dataSource的六种方法

第一种:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
	<property name="url" value="jdbc:oracle:thin:@localhost:1521:oralsb"/>
	<property name="username" value="scott"/>
	<property name="password" value="tiger"/>
</bean>

第二种:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations" value="classpath:jdbc.properties"></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>

第三种:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="properties">
		<value>
			jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
			jdbc.url=jdbc:oracle:thin:@localhost:1521:oralsb 
			jdbc.username=scott
			jdbc.password=tiger
		</value>
	</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>

第四种:(这种需要添加命名空间(xmlns:p=http://www.springframework.org/schema/p))

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	p:driverClassName="oracle.jdbc.driver.OracleDriver" 
	p:url="jdbc:oracle:thin:@localhost:1521:oralsb"
	p:username="scott" 
	p:password="tiger" />

第五种/第六种:

<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 这里的属性class值也可以换成"org.apache.commons.dbcp.BasicDataSource",也就是所谓的第六种 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
</bean>

相关推荐