使用外部属性文件
在配置文件里面配置Bean时,有时需要在Bean的配置里面混入系统部署的细节信息(例如:文件路径,数据源配置信息等)而这些部署细节实际上需要和Bean配置相分离。
Spring提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容外移到属性文件中,可以在Bean配置文件里使用形式为${var}的变量,PropertyPlaceholderConfigurer从属性文件中加载属性,并使用这些属性来替换变量。
Spring还允许在属性文件中使用${propName},以实现属性之间的互相引用。
看下面如何使用外部属性文件
db.properties
user=root password=logan123 driverclass=com.mysql.jdbc.Driver jdbcurl=jdbc:mysql://localhost:3306/test
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <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> </beans>
package logan.spring.study.properties; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) throws SQLException { // TODO Auto-generated method stub ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml"); DataSource datasource = (DataSource) ctx.getBean("dataSource"); System.out.println(datasource.getConnection()); } }
输出结果为:
五月 20, 2017 10:34:14 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7aec35a: startup date [Sat May 20 22:34:14 CST 2017]; root of context hierarchy 五月 20, 2017 10:34:14 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [beans-properties.xml] 五月 20, 2017 10:34:14 下午 com.mchange.v2.log.MLog 信息: MLog clients using java 1.4+ standard logging. 五月 20, 2017 10:34:15 下午 com.mchange.v2.c3p0.C3P0Registry 信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10] 五月 20, 2017 10:34:15 下午 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 -> ggeo7m9oamdcfe1ralrcg|711f39f9, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> ggeo7m9oamdcfe1ralrcg|711f39f9, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test, 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@6366ebe0 [wrapping: com.mysql.jdbc.JDBC4Connection@44f75083]