spring之使用外部属性文件(数据源)

1,首先需要引入两个jar包:c3p0-0.9.1.1.jar   mysql-connector-java-5.1.4.jar,然后配置xml,引入命名空间context:
        <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>
2, 编写外部文件: 并引入到xml中
        user=root;
        password=1230;
       driverclass=com.mysql.jdbc.Driver;
       jdbcurl=jdbc:mysql:///test
3,写main方法:
         public class property {
    public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-properties.xml");
DataSource datasource = (DataSource) ctx.getBean("dataSource");
System.out.println(datasource);
}
}

猜你喜欢

转载自blog.csdn.net/wjc2013481273/article/details/80813724