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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值