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>

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());
}

}
發佈了30 篇原創文章 · 獲贊 0 · 訪問量 1261
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章