Spring 使用外部属性文件配置

1.Spring提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean的配置的部分内容

移到属性文件中。可以在Bean配置文件使用${var}的变量,PropertyPlaceholderConfigurer从属性文件中加载属性。

一般 属性文件后点缀properties

案例:数据源的配置(配置链接数据库的信息)

处理spring 的必须包之外,我们还要导入两个架包

1.数据库的的驱动包

2.C3p0的架包

db-properties.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
 
 
      <!-- 导入属性文件   -->  
    <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>  
</beans>

<!--外部属性文件--->

db.properties
user=root
password=sys123456
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///xbc

写一个测试方法Main,测试是否成功链接数据库

package com.spring.db;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Dbtest {

    public static void main(String[] args) throws SQLException {
        ApplicationContext  ctx=new ClassPathXmlApplicationContext("db-properties.xml");
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println("执行中");
        System.out.println(dataSource.getConnection());
        System.out.println("结束");
    }


   
         

周永发
原文地址:https://www.cnblogs.com/yvanBk/p/8522780.html