spring4-2-bean配置-6-使用外部属性文件
在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离
Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件中. 可以在 Bean 配置文件里使用形式为 ${var} 的变量, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。
一个原始的数据库源配置
1.引入类库-c3p0 和 mysql:
<dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency>
2.配置ComboPooledDataSource数据源bean实例:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/retrieval?characterEncoding=UTF-8"></property> </bean>
3.测试:
public class App { @SuppressWarnings("resource") public static void main(String[] args) throws SQLException { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml"); DataSource ds = ctx.getBean("dataSource",DataSource.class); System.out.println(ds.getConnection()); } }
结果:
六月 18, 2015 10:20:03 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2919d975: startup date [Thu Jun 18 10:20:03 CST 2015]; root of context hierarchy 六月 18, 2015 10:20:03 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [beans-properties.xml] 六月 18, 2015 10:20:04 上午 com.mchange.v2.log.MLog 信息: MLog clients using java 1.4+ standard logging. 六月 18, 2015 10:20:04 上午 com.mchange.v2.c3p0.C3P0Registry 信息: Initializing c3p0-0.9.5.1 [built 16-June-2015 00:06:36 -0700; debug? true; trace: 10] 六月 18, 2015 10:20:04 上午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1bqwdwp9a18ly9s70r2uf|45daddae, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1bqwdwp9a18ly9s70r2uf|45daddae, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://127.0.0.1:3306/retrieval?characterEncoding=UTF-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ] com.mchange.v2.c3p0.impl.NewProxyConnection@79af126e [wrapping: com.mysql.jdbc.JDBC4Connection@54e3322b]
从外部属性文件中读取
1.创建一个属性文件-db.properties
user=root password=root driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://127.0.0.1:3306/retrieval?characterEncoding=UTF-8
2.注册 PropertyPlaceholderConfigurer.使其可以从属性文件中加载属性.
首先引入命名空间context.
<!-- 导入属性文件 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 使用外部属性文件中的属性 --> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> </bean>
这样就完成部署了.
这样做的好处:修改外部属性文件的成本要比修改Spring 配置文件的成本要低的多.