<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerdao" class="com.h3.customer.dao.impl.jdbccustomerdao"> <property name="datasource" ref="datasource" /> </bean> <bean id="customersimpledao" class="com.h3.customer.dao.impl.simplejdbccustomerdao"> <property name="datasource" ref="datasource" /> </bean> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="com.mysql.jdbc.driver" /> <property name="url" value="jdbc:mysql://localhost:3306/h3java" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> </beans>
为了解决这个问题,可以使用 propertyplaceholderconfigurer 类通过一个特殊的格式在外部部署细节到一个属性(properties )文件,以及访问bean的配置文件 – ${variable}.
jdbc.driverclassname=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/h3_db jdbc.username=root jdbc.password=123456
<bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <property name="location"> <value>database.properties</value> </property> </bean>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <property name="location"> <value>database.properties</value> </property> </bean> <bean id="customerdao" class="com.h3.customer.dao.impl.jdbccustomerdao"> <property name="datasource" ref="datasource" /> </bean> <bean id="customersimpledao" class="com.h3.customer.dao.impl.simplejdbccustomerdao"> <property name="datasource" ref="datasource" /> </bean> <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> </beans>