`
enica
  • 浏览: 69251 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

}

来自http://www.cublog.cn/u/9295/showart_261437.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics