Spring 运用Properties配置文件
1.
jdbc.properties
database.url=jdbc:mysql://localhost/smaple
database.driver=org.gjt.mm.mysql.Driver
database.user=root
database.password=star1xing
2.conf.xml
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>com/starxing/test/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>${database.url}</value>
</property>
<property name="driverClassName">
<value>${database.driver}</value>
</property>
<property name="username">
<value>${database.user}</value>
</property>
<property name="password">
<value>${database.password}</value>
</property>
</bean>
</beans>
当放入多个配置文件时
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>>classpath:system1.properties</value>
<value>>classpath:system2.properties</value>
</list>
</property>
</bean>
还可以这样
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:*.properties</value>
</list>
</property>
</bean>
3.Config.java
package com.starxing.test;
import
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import
org.springframework.beans.factory.xml.XmlBeanFactory;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
org.springframework.core.io.FileSystemResource;
import
org.springframework.jdbc.datasource.DriverManagerDataSource;
public class
Config {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"com/starxing/test/conf.xml"));
//
如果要在
BeanFactory
中使用,
bean
factory post-processor
必须手动运行
:
PropertyPlaceholderConfigurer cfg = new
PropertyPlaceholderConfigurer();
cfg.setLocation(new
FileSystemResource(
"com/starxing/test/jdbc.properties"));
cfg.postProcessBeanFactory(factory);
DriverManagerDataSource
dataSource = (DriverManagerDataSource) factory
.getBean("dataSource");
System.out.println(dataSource.getDriverClassName());
//
注意,
ApplicationContext
能够自动辨认和应用在其上部署的实现了
BeanFactoryPostProcessor
的
bean
。这就意味着,当使用
ApplicationContext
的时候应用
PropertyPlaceholderConfigurer
会非常的方便。由于这个原因,建议想要使用这个或者其他
bean
// factory postprocessor
的用户使用
ApplicationContext
代替
BeanFactroy
。
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/starxing/test/conf.xml");
DriverManagerDataSource
dataSource2 = (DriverManagerDataSource) context
.getBean("dataSource");
System.out.println(dataSource2.getDriverClassName());
}
}