通常,大多数Spring开发人员只是将整个部署详细信息(数据库详细信息,日志文件路径)放在XML 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 id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="customerSimpleDAO" class="com.mkyong.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/mkyongjava" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
</beans>
但是,在公司环境中,部署细节通常只能由系统或数据库管理员“触摸”,他们只是拒绝直接访问您的bean配置文件,并且他们将为部署配置请求一个单独的文件,例如,简单属性,仅包含部署详细信息。
PropertyPlaceholderConfigurer示例
要解决此问题,可以使用PropertyPlaceholderConfigurer类将部署详细信息外部化为属性文件,并通过特殊格式$ {variable}从bean配置文件进行访问。
创建一个属性文件(database.properties),包括数据库详细信息,并将其放入项目类路径中。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongjava
jdbc.username=root
jdbc.password=password
在bean配置文件中声明一个PropertyPlaceholderConfigurer并映射到您刚才创建的' database.properties
'属性文件。
<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.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="customerSimpleDAO"
class="com.mkyong.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>
替代用法
您还可以使用PropertyPlaceholderConfigurer与所有其他bean共享一些常量。 例如,在属性文件中定义日志文件位置,然后通过${log.filepath}
从其他bean配置文件访问属性值。
下载源代码
标签: 春天
翻译自: https://mkyong.com/spring/spring-propertyplaceholderconfigurer-example/