Spring 使用外部属性文件

  • 在配置文件里配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源配置信息等),而这些部署细节实际上需要和Bean配置分离
  • Spring 提供了一个 PropertyPlaceHolderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容移到属性文件中,可以在Bean配置文件里使用形式为${}的变量,PropertyPlaceHolderConfigurer从属性文件里加载属性,并使用这些属性来替换变量。
  • Spring还允许在属性文件中使用${propName},从实现属性之间的相互引用。
  1. // src/applicationCentext.xml
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  11. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  12. <property name="user" value="root"></property>
  13. <property name="password" value="1230"></property>
  14. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  15. <property name="jdbcUrl" value="jdbc:mysql:///test"></property>
  16. </bean>
  17. </beans>
  18. // src/db.propertyies
  19. user=root
  20. password=1230
  21. driverclass=com.mysql.jdbc.Driver
  22. jdbcurl=jdbc:mysql:///test
  23. // 修改 src/applicationCentext.xml
  24. <?xml version="1.0" encoding="UTF-8"?>
  25. <beans xmlns="http://www.springframework.org/schema/beans"
  26. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  27. xmlns:context="http://www.springframework.org/schema/context"
  28. xsi:schemaLocation="
  29. http://www.springframework.org/schema/beans
  30. http://www.springframework.org/schema/beans/spring-beans.xsd
  31. http://www.springframework.org/schema/context
  32. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  33. <context:property-placeholder location="classpath:db.properties" />
  34. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  35. <property name="user" value="${root}"></property>
  36. <property name="password" value="${password}"></property>
  37. <property name="driverClass" value="${driverclass}"></property>
  38. <property name="jdbcUrl" value="${jdbcurl}"></property>
  39. </bean>
  40. </beans>

image.png